Analysis of four basic Java encryption algorithms

  • 2020-06-07 04:28:24
  • OfStack

Analysis of Java 4 basic encryption algorithms

Simple java encryption algorithm:

BASE64 is strictly a coding format, not an encryption algorithm MD5(Message Digest algorithm 5, Information Summary Algorithm) SHA(Secure Hash Algorithm, secure hashing algorithm) HMAC(Hash Message Authentication Code, Hash message authentication code)

1. BASE64

Base64 is one of the most common encoding methods used to transmit 8Bit byte code on the network. You can check out RFC2045 ~ RFC2049 with detailed specifications for MIME. The Base64 encoding can be used to pass long identification messages in the HTTP environment. For example, in Java Persistence system hibernate, Base64 is used to encode a longer 1-only identifier (1 UUID, typically 128-ES36en) into a string as a parameter in HTTP form and HTTP GET URL. In other applications, it is also common to encode base 2 data in a form suitable for URL, including hidden form fields. At this point, the Base64 encoding is not readable, that is, the encoded data will not be seen directly by human eyes. (Source: Baidu.com)

java implementation code:


package com.cn. One-way encryption ;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/*
BASE64 Encryption and decryption is two-way, you can find the reverse solution .
BASE64Encoder and BASE64Decoder Is the official JDK The implementation class. Although it can be done in JDK Can be found and used, but in API Richard couldn't find it. 
JRE  In the  sun  and  com.sun  The classes that begin the package are undocumented and belong to  java, javax  The foundation of a class library, most of whose implementation is related to the underlying platform, 
1 Generally speaking, it is not recommended.  
BASE64  Strictly speaking, it belongs to encoding format, not encryption algorithm  
 The main is BASE64Encoder , BASE64Decoder Two classes, we just need to know to use the corresponding method. 
 On the other, BASE The number of bytes produced after encryption is 8 If the number of digits is not enough = Symbol padding.  
BASE64 
 In accordance with the RFC2045 The definition, Base64 Defined as: Base64 Content transfer encoding is designed to take arbitrary sequences 8 Bit bytes are described as 1 A form that is not readily identifiable by others. 
 ( The Base64 Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable. )  
 Common in mail, http Encrypt, intercept http Information, you will find the login operation of the username and password fields through BASE64 Encrypted. 
*/

public class BASE64 {
  /** 
   * BASE64 decryption  
   *  
   * @param key 
   * @return 
   * @throws Exception 
   */ 
  public static byte[] decryptBASE64(String key) throws Exception {  
    return (new BASE64Decoder()).decodeBuffer(key);  
  }  

  /** 
   * BASE64 encryption  
   *  
   * @param key 
   * @return 
   * @throws Exception 
   */ 
  public static String encryptBASE64(byte[] key) throws Exception {  
    return (new BASE64Encoder()).encodeBuffer(key);  
  } 

  public static void main(String[] args) {

   String str="12345678";

    try {
    String result1= BASE64.encryptBASE64(str.getBytes());
     System.out.println("result1===== Encrypt the data =========="+result1);

     byte result2[]= BASE64.decryptBASE64(result1);
     String str2=new String(result2);
     System.out.println("str2======== Decrypt the data ========"+str2);
  } catch (Exception e) {
    e.printStackTrace();
  }

  }

}

2. MD5

MD5, or ES54en-ES55en Algorithm 5 (information-summary algorithm 5), is used to ensure the integrity of the information transmission. It is one of the widely used hash algorithms in computers, and MD5 has been widely implemented in mainstream programming languages. The basic principle of the hashing algorithm is to calculate the data (such as Chinese characters) into another fixed length value. The predecessor of MD5 is MD2, MD3 and MD4. Widely used in encryption and decryption techniques, often used in file verification. Check? Regardless of the size of the file, MD5 generates a value of MD5 that is unique to 1. For example, the current ISO checksum is MD5. How does it work? Of course, ISO is passed through MD5 to produce the value of MD5. Most people who have downloaded ES69en-ES70en have seen the string MD5 next to the download link. It is used to verify that the file is sent to 1.

java implementation:


package com.cn. One-way encryption ;

import java.math.BigInteger;
import java.security.MessageDigest;
/*
MD5(Message Digest algorithm 5 , information summary algorithm ) 
 Usually we don't use the above directly MD5 Encryption. Will usually MD5 The resulting byte array is handed over BASE64 Encrypted again 1 Take, and get the corresponding string 
Digest: assembly 
*/
public class MD5 {
  public static final String KEY_MD5 = "MD5";  

  public static String getResult(String inputStr)
  {
    System.out.println("======= Data before encryption :"+inputStr);
    BigInteger bigInteger=null;

    try {
     MessageDigest md = MessageDigest.getInstance(KEY_MD5);  
     byte[] inputData = inputStr.getBytes(); 
     md.update(inputData);  
     bigInteger = new BigInteger(md.digest());  
    } catch (Exception e) {e.printStackTrace();}
    System.out.println("MD5 encrypted :" + bigInteger.toString(16));  
    return bigInteger.toString(16);
  }

  public static void main(String args[])
  {
    try {
       String inputStr = " Simple encryption 8888888888888888888";  
       getResult(inputStr);
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}

MD5 algorithm has the following characteristics:

1. Compressibility: The calculated MD5 value has a fixed length for any length of data.
2. Easy to calculate: It is easy to calculate the value of MD5 from the original data.
3. Modifiability: If you modify the original data by even one byte, the value of MD5 will be very different.
4. Weak collision resistance: given the original data and its MD5 value, it is very difficult to find a data with the same MD5 value (i.e., forged data).
5. Strong collision resistance: It is very difficult to find two different data that have the same VALUE of MD5.
The purpose of MD5 is to "compress" large amounts of information into a secure format (that is, convert an arbitrary length byte string into a fixed length hexadecimal digit string) before signing the private key with digital signature software. In addition to MD5, the famous ones are ES94en-1, RIPEMD and Haval.

3.SHA

Secure hashing algorithm (Secure Hash Algorithm) mainly applies to the digital signature algorithm defined in the digital signature standard (Digital Standard DSS) (Digital Signature Algorithm DSA). SHA1 produces a 160-bit message digest for messages of length less than 2^64 bits. After years of development and improvement by encryption experts, the algorithm has been increasingly perfect and widely used. Ideas of the algorithm is receiving 1 period of plaintext, and then in an irreversible way to convert it into one paragraph (usually less) ciphertext, can also be simply interpreted as one string input code (called mapping or information), and put them into shorter length, the output sequence of digits fixed the hash value (also known as the information or message authentication code) process. A hash function value can be said to be a "fingerprint" or "summary" of the plaintext so a digital signature of the hash value can be considered a digital signature of the plaintext.

java implementation:


package com.cn. One-way encryption ;

import java.math.BigInteger;
import java.security.MessageDigest;

/*
SHA(Secure Hash Algorithm , secure hashing algorithm), digital signature and other important tools in cryptography applications, 
 It is widely used in electronic commerce and other information security fields. Although, SHA with MD5 It's been cracked by collision,  
 but SHA Still recognized as a secure encryption algorithm, compared to MD5 More secure */
public class SHA {
   public static final String KEY_SHA = "SHA";  

  public static String getResult(String inputStr)
  {
    BigInteger sha =null;
    System.out.println("======= Data before encryption :"+inputStr);
    byte[] inputData = inputStr.getBytes();  
    try {
       MessageDigest messageDigest = MessageDigest.getInstance(KEY_SHA); 
       messageDigest.update(inputData);
       sha = new BigInteger(messageDigest.digest());  
       System.out.println("SHA encrypted :" + sha.toString(32));  
    } catch (Exception e) {e.printStackTrace();}
    return sha.toString(32);
  }

  public static void main(String args[])
  {
    try {
       String inputStr = " Simple encryption ";  
       getResult(inputStr);
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}

Comparison between SHA-1 and MD5

Since both are derived from MD4, ES125en-1 and MD5 are very similar to each other. Accordingly, their strength and other characteristics are similar, but there are several differences as follows:
Security of l against forced attacks: The most significant and important difference is that the SHA-1 abstract is 32 bits longer than the MD5 abstract. Using the force technique, the difficulty of producing any 1 message whose summary is equal to the given message summary is order of 2^128 for MD5 and order of 2^160 for SHA-1. Thus, SHA-1 has greater strength against forced attacks.

l security against cryptanalysis: MD5 is designed to be vulnerable to cryptanalysis, while SHA-1 is not.
l speed: ON the same hardware, SHA-1 runs slower than MD5.

4.HMAC

HMAC(Hash Message Authentication Code, Hash message authentication code, key based Hash algorithm authentication protocol. The principle of message authentication code is to use the public function and key to produce a fixed length value as the authentication identifier, which is used to authenticate the integrity of the message. A small fixed-size block of data, MAC, is generated using a key, added to the message, and then transmitted. The receiver USES the key Shared with the sender for authentication and so on.

java implementation code:


package com.cn. One-way encryption ;
/*
HMAC 
HMAC(Hash Message Authentication Code Hash message authentication code based on the key Hash Algorithm authentication protocol. 
 Message identifiers are generated using public functions and keys 1 A value of a fixed length is used as an authentication identifier to identify the integrity of the message. 
 use 1 Individual key generation 1 A small fixed-size block of data, 
 namely MAC , and add it to the message, and then transfer it. The receiver USES the key Shared with the sender for authentication and so on. */
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.cn.comm.Tools;

/** 
 *  Base encryption component  
 */ 
public abstract class HMAC {  
  public static final String KEY_MAC = "HmacMD5";  

  /** 
   *  Initialize the HMAC The key  
   *  
   * @return 
   * @throws Exception 
   */ 
  public static String initMacKey() throws Exception {  
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);  
    SecretKey secretKey = keyGenerator.generateKey();  
    return BASE64.encryptBASE64(secretKey.getEncoded());  
  }  

  /** 
   * HMAC encryption   : Main methods 
   *  
   * @param data 
   * @param key 
   * @return 
   * @throws Exception 
   */ 
  public static String encryptHMAC(byte[] data, String key) throws Exception {  

    SecretKey secretKey = new SecretKeySpec(BASE64.decryptBASE64(key), KEY_MAC);  
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());  
    mac.init(secretKey);  
    return new String(mac.doFinal(data));  

  }  

  public static String getResult1(String inputStr)
  {
    String path=Tools.getClassPath();
    String fileSource=path+"/file/HMAC_key.txt";
    System.out.println("======= Data before encryption :"+inputStr);
    String result=null;
    try {
      byte[] inputData = inputStr.getBytes(); 
      String key = HMAC.initMacKey(); /* Have the key */ 
      System.out.println("Mac The key :===" + key); 
      /* Write the key to a file */
      Tools.WriteMyFile(fileSource,key);
      result= HMAC.encryptHMAC(inputData, key);
      System.out.println("HMAC encrypted :===" + result); 
    } catch (Exception e) {e.printStackTrace();} 
    return result.toString();
  }

  public static String getResult2(String inputStr)
  {
    System.out.println("======= Data before encryption :"+inputStr);
     String path=Tools.getClassPath();
     String fileSource=path+"/file/HMAC_key.txt";
     String key=null;;
    try {
       /* Read the key from the file */
       key=Tools.ReadMyFile(fileSource);
       System.out.println("getResult2 The key :===" + key); 
    } catch (Exception e1) {
      e1.printStackTrace();}
    String result=null;
    try {
      byte[] inputData = inputStr.getBytes(); 
      /* Encrypt the data */
      result= HMAC.encryptHMAC(inputData, key);
      System.out.println("HMAC encrypted :===" + result); 
    } catch (Exception e) {e.printStackTrace();} 
    return result.toString();
  }

  public static void main(String args[])
  {
    try {
       String inputStr = " Simple encryption "; 
       /* Use the same 1 Key: Encrypt the data: See if the result of two encryptions is correct 1 sample */
       getResult1(inputStr); 
       getResult2(inputStr);

    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: