Share four commonly used Java encryption algorithms of

  • 2020-04-01 04:13:55
  • OfStack

Symmetric encryption algorithm is an early encryption algorithm with mature technology. In symmetric encryption algorithm, the data sender makes the plaintext (raw data) and the encryption key (mi yue) into a complex encrypted ciphertext after being processed by a special encryption algorithm. After receiving the ciphertext, if the recipient wants to interpret the original text, it needs to decrypt the ciphertext using the encryption key used and the inverse algorithm of the same algorithm, so that the ciphertext can be restored to readable plaintext. In symmetric encryption algorithm, only one key is used, and both sending and receiving parties use this key to encrypt and decrypt the data, which requires the decryption party to know the encryption key in advance.

Simple Java encryption algorithm is:

BASE is strictly an encoding format, not an encryption algorithm
MD(Message Digest algorithm)
SHA(Secure Hash Algorithm)
HMAC(Hash Message Authentication Code)

The first one is.base

Base is one of the most common encoders on the network for transmitting bits of bytecode. Check out RFC ~ RFC for detailed MIME specifications. The Base encoding can be used to pass long identity information in an HTTP environment. For example, in the Java Persistence system Hibernate, Base is used to encode a long unique identifier (typically a UUID of -bit) as a string that is used as a parameter in the HTTP form and the HTTP GET URL. In other applications, it is also common to encode binary data in a form suitable for placing in urls, including hidden form fields. At this point, the Base encoding is not readable, that is, the encoded data will not be directly seen by the naked eye. (source: baidubaike)

Java implementation code:


package com.cn. One-way encryption ;
import sun.misc.BASEDecoder;
import sun.misc.BASEEncoder;

public class BASE {
   
  public static byte[] decryptBASE(String key) throws Exception { 
    return (new BASEDecoder()).decodeBuffer(key); 
  } 
   
  public static String encryptBASE(byte[] key) throws Exception { 
    return (new BASEEncoder()).encodeBuffer(key); 
  } 
  public static void main(String[] args) {
   String str="";
    try {
    String result= BASE.encryptBASE(str.getBytes());
     System.out.println("result===== Encrypt the data =========="+result);
     byte result[]= BASE.decryptBASE(result);
     String str=new String(result);
     System.out.println("str======== Decrypt the data ========"+str);
  } catch (Exception e) {
    e.printStackTrace();
  }
  }
}

The second type. MD

MD, or message-digest Algorithm, is used to ensure complete and consistent transmission of information. It is one of the hash algorithms widely used in computer. The operation of data (such as Chinese characters) into another fixed length value is the basic principle of hash algorithm. Widely used in encryption and decryption techniques, often used for file verification. Check? No matter how big the file is, the unique MD value can be generated after MD. Like the current ISO calibration, are MD calibration. How does it work? Of course, the ISO through MD produces the value of MD. Most friends who download linux-iso have seen the string of MD next to the download link. Is used to verify that the file is consistent.

Java implementation:


package com.cn. One-way encryption ;
import java.math.BigInteger;
import java.security.MessageDigest;

public class MD {
  public static final String KEY_MD = "MD"; 
  public static String getResult(String inputStr)
  {
    System.out.println("======= Pre-encrypted data :"+inputStr);
    BigInteger bigInteger=null;
    try {
     MessageDigest md = MessageDigest.getInstance(KEY_MD); 
     byte[] inputData = inputStr.getBytes();
     md.update(inputData); 
     bigInteger = new BigInteger(md.digest()); 
    } catch (Exception e) {e.printStackTrace();}
    System.out.println("MD encrypted :" + bigInteger.toString()); 
    return bigInteger.toString();
  }
  public static void main(String args[])
  {
    try {
       String inputStr = " Simple encryption "; 
       getResult(inputStr);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

MD algorithm has the following characteristics:

Compressibility: for data of any length, the length of the calculated MD value is fixed.
Easy to calculate: it is easy to calculate the MD value from the original data.
Resistance to modification: any modification of the original data, even if only a byte of modification, the value of MD obtained are very different.
, weak collision resistance: given the original data and its MD value, it is very difficult to find a data with the same MD value (that is, to forge the data).
Strong collision resistance: it is very difficult to find two different data that have the same MD value.

The role of MD is to allow large amounts of information to be "compressed" into a secure format (that is, to convert an arbitrarily long byte string into a hexadecimal number string) before signing the private key with digital signature software. In addition to MD, the more famous ones are sha-ripemd, Haval, etc.

The third kind. SHA

Secure Hash Algorithm is mainly applicable to Digital Signature Algorithm DSA defined in Digital Signature Standard DSS. For messages of length less than ^ bit, SHA produces a bit message digest. After years of development and improvement by encryption experts, the algorithm has been increasingly perfect and widely used. Ideas of the algorithm is to receive a Duan Mingwen, then in an irreversible way to convert it to a (usually less) ciphertext, can also be a simple understanding to take a series of 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. The hash function value can be said to be a "fingerprint" or "digest" of the plaintext so that a digital signature of the hash value can be considered as a digital signature of the plaintext.

Java implementation:


package com.cn. One-way encryption ;
import java.math.BigInteger;
import java.security.MessageDigest;

public class SHA {
   public static final String KEY_SHA = "SHA"; 
  public static String getResult(String inputStr)
  {
    BigInteger sha =null;
    System.out.println("======= Pre-encrypted data :"+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()); 
    } catch (Exception e) {e.printStackTrace();}
    return sha.toString();
  }
  public static void main(String args[])
  {
    try {
       String inputStr = " Simple encryption "; 
       getResult(inputStr);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Sha-compare to MD

Since both are derived from MD, sha-md is very similar to each other. Correspondingly, their strength and other characteristics are similar, but there are several differences:

Security against forced attacks: the most significant and important difference is that the sha-digest is longer than the MD digest. Using forced technique, the difficulty of producing any message whose digest is equal to a given digest is an order of magnitude operation for MD and an order of magnitude operation for SHA-. In this way, sha-has greater strength against forced attacks.

Security against cryptanalysis: because of the design of MD, it is vulnerable to cryptanalysis, and sha-appears to be vulnerable to such attacks.

Speed: sha-runs slower than MD on the same hardware.

Fourth, HMAC

HMAC(Hash Message Authentication Code) Message authentication codes implement authentication by using public functions and keys to generate a fixed-length value as the authentication identifier, which is used to authenticate the integrity of the message. A small fixed-size chunk of data, a MAC, is generated using a key, added to the message, and then transferred. The receiver USES the key Shared with the sender for authentication, etc.

Java implementation code:


package com.cn. One-way encryption ;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.cn.comm.Tools;
 
public abstract class HMAC { 
  public static final String KEY_MAC = "HmacMD"; 
   
  public static String initMacKey() throws Exception { 
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC); 
    SecretKey secretKey = keyGenerator.generateKey(); 
    return BASE.encryptBASE(secretKey.getEncoded()); 
  } 
   
  public static String encryptHMAC(byte[] data, String key) throws Exception { 
    SecretKey secretKey = new SecretKeySpec(BASE.decryptBASE(key), KEY_MAC); 
    Mac mac = Mac.getInstance(secretKey.getAlgorithm()); 
    mac.init(secretKey); 
    return new String(mac.doFinal(data)); 
  } 
  public static String getResult(String inputStr)
  {
    String path=Tools.getClassPath();
    String fileSource=path+"/file/HMAC_key.txt";
    System.out.println("======= Pre-encrypted data :"+inputStr);
    String result=null;
    try {
      byte[] inputData = inputStr.getBytes();
      String key = HMAC.initMacKey();  
      System.out.println("Mac The key :===" + key); 
      
      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 getResult(String inputStr)
  {
    System.out.println("======= Pre-encrypted data :"+inputStr);
     String path=Tools.getClassPath();
     String fileSource=path+"/file/HMAC_key.txt";
     String key=null;;
    try {
       
       key=Tools.ReadMyFile(fileSource);
       System.out.println("getResult The key :===" + key); 
    } catch (Exception e) {
      e.printStackTrace();}
    String result=null;
    try {
      byte[] inputData = inputStr.getBytes(); 
      
      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 ";
       
       getResult(inputStr);
       getResult(inputStr);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

The above content is this site to share several common Java encryption algorithms (four), I hope you like.


Related articles: