Common encryption modes in java

java encryption algorithms include:
1. BASE64 strictly speaking, it belongs to encoding format, not encryption algorithm
2. Summary algorithm
3. Symmetric encryption
4. Asymmetric encryption

1, Base64 encoding can be used to pass long identity information in HTTP environment. For example, in the Java Persistence system Hibernate, Base64 is used to encode a long unique identifier (usually a 128 bit UUID) into a string, which is used as a parameter in the HTTP form and HTTP GET URL. In other applications, binary data is often encoded in a form suitable for placement in URLs, including hidden form fields. At this time, Base64 encoding is unreadable, that is, the encoded data will not be directly seen by human eyes.
Before jdk1.8, you need to rely on a third-party library to support Base64 encoding. After 1.8 and added to the official library of java8, you can directly use the base64 class for encoding and decoding

package com.qian.encoded;
import java.util.Base64;
public class Base64Test {
    public static void main(String[] args) {
        String str =  "Come on China, come on Wuhan!";
        Base64.Encoder encoder = Base64.getEncoder();
        Base64.Decoder decoder= Base64.getDecoder();
        String encodeStr = encoder.encodeToString(str.getBytes());
        System.out.println("After encryption str: "+encodeStr);
        String decoderStr  = new String (decoder.decode(encodeStr));
        System.out.println("After decryption str: "+decoderStr);
    }
}

2, Summary algorithm
Message digest algorithm is used to verify the integrity of data, which is divided into three categories
MD(Message Digest): Message Digest
SHA(Secure Hash Algorithm): secure hash
MAC(Message Authentication Code): message authentication code
The most common encryption processing of login password, MD5 encryption, MD5 belongs to message digest, which can be used to ensure that the content is not tampered with: password encryption, file verification code
For the encryption types supported by JDK8, please refer to: https://docs.oracle.com/javase/8/docs/technologies/guides/security/standardnames.html × messagedigest

import java.math.BigInteger;
import java.security.MessageDigest;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * One way encryption, message summary
 * Digest
 * 
 */
public class Digest {
    private static String KEY_MD5 = "MD5";
    private static String KEY_SHA = "SHA";
    private static String KEY_MAC = "HmacMD5";
    /**
     * md5 encryption
     * <br/>
     * MD5 -- message-digest algorithm 5 (Information summary algorithm),
     * Widely used in encryption and decryption technology, commonly used in file verification. The size of the management file can generate a unique MD5 value after MD5.
     * 
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encryptMD5(byte[] data) throws Exception {  
        MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
        md5.update(data);  
        return md5.digest();  
    }
    /**
     * sha encryption
     * <br/>
     * SHA(Secure Hash Algorithm,Secure hash algorithm),
     * Digital signature and other important tools in cryptography applications are widely used in e-commerce and other information security fields.
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encryptSHA(byte[] data) throws Exception {  
        MessageDigest md5 = MessageDigest.getInstance(KEY_SHA);
        md5.update(data);  
        return md5.digest();  
    }
    
    /** 
          * Initialize HMAC key 
     *  
     * @return 
     * @throws Exception 
     */  
    public static byte[] initMacKey() throws Exception {  
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);  
        SecretKey secretKey = keyGenerator.generateKey();  
        return secretKey.getEncoded();  
    }  
  
    /** 
     * HMAC encryption 
     * <br/>
     *  HMAC(Hash Message Authentication Code,Hash message identifier,
     *  Authentication protocol of Hash algorithm based on key. The principle of message authentication code is,
     *  The public function and the key are used to generate a fixed length value as the authentication identifier, which is used to authenticate the integrity of the message.
     *  A key is used to generate a fixed size small data block, namely MAC, and add it to the message,
     *  Then transmit. The receiver uses the key shared with the sender for authentication. 
     * @param data 
     * @param key 
     * @return 
     * @throws Exception 
     */  
    public static byte[] encryptHMAC(byte[] data, byte[] key) throws Exception {  
  
        SecretKey secretKey = new SecretKeySpec(key, KEY_MAC);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());  
        mac.init(secretKey);  
        return mac.doFinal(data);
  
    }  
    
    public static void main(String[] args) {
        try {
            byte[] md5 = encryptMD5("hello".getBytes());
            System.out.println("hello md5: "+new BigInteger(md5).toString(16));
            
            byte[] sha = encryptSHA("hash".getBytes());
            System.out.println("hash sha: "+new BigInteger(sha).toString(16));
            
            byte[] macKey = initMacKey();
            byte[] hmac = encryptHMAC("hello hash".getBytes(), macKey);
            System.out.println("hello hash key: "+new BigInteger(macKey).toString(16)
                    +"\r\n encrypt: "+new BigInteger(hmac).toString(16));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


3, Symmetric encryption
DES(Data Encryption Standard)
PBE (password based encryption)

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
 * DES-Data Encryption Standard,Data encryption algorithm. DES security coding component,
 * DES There are three entry parameters of the algorithm: Key, Data and Mode.
 * The Key is the working Key of DES algorithm with 8 bytes of 64 bits in total; the Data is also the 64 bits of 8 bytes,
 * Data to be encrypted or decrypted;
 * Mode There are two ways for DES to work: encryption or decryption. DESCoder
 * 
 */
public class DESCoder {
    public static final String ALGORITHM = "DES";
    /**
     * Conversion key
     * 
     * @param key
     * @return
     * @throws Exception
     */
    private static Key toKey(byte[] key) throws Exception {
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(dks);
        // When using other symmetric encryption algorithms, such as AES and Blowfish, replace the above three lines with the following code
        // SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);

        return secretKey;
    }

    /**
     * encryption
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, k);

        return cipher.doFinal(data);
    }

    /**
     * Decrypt
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, k);

        return cipher.doFinal(data);
    }

    /**
     * Generating key
     * 
     * @return
     * @throws Exception
     */
    public static byte[] initKey() throws Exception {
        return initKey("1111".getBytes());
    }

    /**
     * Generating key
     * 
     * @param seed
     * @return
     * @throws Exception
     */
    public static byte[] initKey(byte[] seed) throws Exception {
        SecureRandom secureRandom = null;
        if (seed != null) {
            secureRandom = new SecureRandom(seed);
        } else {
            secureRandom = new SecureRandom();
        }
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
        kg.init(secureRandom);
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }

    public static void main(String[] args) {
        try {
            String inputStr = "DES";
            byte[] key = DESCoder.initKey();
            System.err.println("original text:\t" + inputStr);
            System.err.println("secret key:\t" + key);
            byte[] inputData = inputStr.getBytes();
            inputData = DESCoder.encrypt(inputData, key);
            System.err.println("After encryption:\t" + inputData);
            byte[] outputData = DESCoder.decrypt(inputData, key);
            String outputStr = new String(outputData);
            System.err.println("After decryption:\t" + new String(outputStr));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


4, Asymmetric encryption

Tags: Programming Mac Java encoding Hibernate

Posted on Wed, 11 Mar 2020 01:00:53 -0400 by Ellen67