What are your common encryption algorithms?

Encryption algorithms can be divided into reversible encryption and irreversible encryption, and reversible encryption can be divided into symmetric encryption and asymmetric encryption.

1, Irreversible encryption

Common irreversible encryption algorithms include MD5, HMAC, SHA1, SHA-224, SHA-256, SHA-384, and SHA-512. Among them, SHA-224, SHA-256, SHA-384, and SHA-512 can be collectively referred to as SHA2 encryption algorithm. The security of Sha encryption algorithm is higher than MD5, and SHA2 encryption algorithm is higher than SHA1. The number after Sha represents the length of the encrypted string. SHA1 will generate a 160 bit information summary by default.

The biggest feature of irreversible encryption algorithm is the key, but HMAC needs the key [manual dog head].

Because these encryptions are irreversible, the most common scenario is user password encryption. The verification process is to confirm the identity by comparing whether the two encrypted strings are the same. There are also many websites on the Internet that claim to be able to crack the MD5 password. The principle is the same, that is, there is a huge resource library, which stores many strings and the corresponding MD5 encrypted strings. Compare them through the MD5 encrypted strings you enter. If your password complexity is relatively low, there is still a great chance to verify it.

1.1 MD5

MD5 message digest algorithm (English: MD5 message digest algorithm), a widely used cryptographic hash function, can generate a 128 bit (16 byte) hash value to ensure the integrity and consistency of information transmission.

MD5 algorithm has the following characteristics:

1. Compressibility: no matter how long the data is, the length of the calculated MD5 value is the same

2. Easy to calculate: MD5 value can be easily calculated from the original data

3. Modification resistance: even if one byte is modified, the calculated MD5 value will be greatly different

4. Collision resistance: knowing the data and MD5 value, it is very unlikely to find the original data with the same MD5 value.

public static String md5(String text) {
    MessageDigest messageDigest = null;
    try {
        messageDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    byte[] bytes = messageDigest.digest(text.getBytes());
    return Hex.encodeHexString(bytes); 
}

1.2 SHA series

Secure Hash Algorithm (English: Secure Hash Algorithm, abbreviated as SHA) is a family of cryptographic hash functions, which is a Secure Hash Algorithm certified by FIPS. An algorithm that can calculate a fixed length string (also known as message digest) corresponding to a digital message. And if the input messages are different, they have a high probability of corresponding to different strings.
At the end of the CRYPTO meeting on August 17, 2005, Wang Xiaoyun, Yao Qizhi and Yao chufeng once again published a more efficient SHA-1 attack method, which can find collisions within the 63rd power of 2.

In other words, SHA-1 encryption algorithm has the possibility of collision, although it is very small.

public static String sha256(String text) {
    MessageDigest messageDigest = null;
    try {
        messageDigest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    byte[] bytes = messageDigest.digest(text.getBytes()); 
    return Hex.encodeHexString(bytes); 
}

1.3 HMAC series

HMAC is the abbreviation of key related Hash based message authentication code. It is a method of message authentication based on Hash function and key proposed by H.Krawezyk, M.Bellare and R.Canetti in 1996. It was published as RFC2104 in 1997 and has been widely used in IPSec and other network protocols (such as SSL). Now it has become a de facto Internet security standard. It can be used in conjunction with any iterative Hash function.
HMAC algorithm is more like an encryption algorithm. It introduces a key, and its security does not completely depend on the Hash algorithm used

public static String hmacSha256(String text, SecretKeySpec sk) {
    Mac mac = null;
    try {
        mac = Mac.getInstance("HmacSHA256");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    try {
        mac.init(sk);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    byte[] rawHmac = mac.doFinal(text.getBytes());
    return new String(Base64.encodeBase64(rawHmac));
}

If irreversible encryption is to be used, SHA256, SHA384, SHA512 and HMAC-SHA256, HMAC-SHA384 and HMAC-SHA512 algorithms are recommended.

2, Symmetric encryption algorithm

Symmetric encryption algorithm is an early algorithm. The same key is used in data encryption and decryption, which leads to the difficulty of key management. Common symmetric encryption algorithms include DES, 3DES, AES128, AES192 and AES256 (the JDK installed by default does not support AES256, and the corresponding JCE patches need to be installed to upgrade jce1.7 and jce1.8). The number after AES represents the key length. The security of symmetric encryption algorithm is relatively low. The more applicable scenario is encryption and decryption in Intranet environment.

2.1 DES
DES is a typical algorithm in the field of symmetric encryption algorithm. The default length of its key is 56 bits.

// encryption
public static String encrypt(byte[] dataSource, String password){
     try {
         SecureRandom random = new SecureRandom();
         DESKeySpec desKeySpec = new DESKeySpec(password.getBytes());
         //Create a key factory and use it to convert DESKeySpec into 
         SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES"); 
         SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec); 
         //Cipher object actually completes the encryption operation 
         Cipher cipher = Cipher.getInstance("DES"); 
         //Initializing Cipher objects with keys 
         cipher.init(Cipher.ENCRYPT_MODE, secretKey, random); 
         //Officially perform encryption operation 
         return Base64.encodeBase64String(cipher.doFinal(dataSource)); 
     } catch (Throwable e) { 
         e.printStackTrace(); 
     } return null; 
 } 
// decrypt
public static String decrypt(String src, String password) throws Exception{ 
    // DES algorithm requires a trusted random number source 
    SecureRandom random = new SecureRandom(); 
    // Create a DESKeySpec object 
    DESKeySpec desKeySpec = new DESKeySpec(password.getBytes()); 
    // Create a key factory 
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 
    // Convert the DESKeySpec object to a SecretKey object 
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec); 
    // The Cipher object actually completes the decryption operation 
    Cipher cipher = Cipher.getInstance("DES"); 
    // Initializing Cipher objects with keys 
    cipher.init(Cipher.DECRYPT_MODE, secretKey, random); 
    // Really start decryption operation 
    return new String(cipher.doFinal(Base64.decodeBase64(src))); 
}

2.2 3DES
3DES (Triple DES) is an encryption algorithm for the transition from des to AES. It uses three 56 bit keys to encrypt the data three times. It is a safer deformation of Des. It takes des as the basic module and designs the grouping encryption algorithm through the combined grouping method. 3DES is safer than the original des. The key length is 168 bits by default, and 128 bits can be selected.

public static String encryptThreeDESECB(String src, String key) {
    try{
        DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey securekey = keyFactory.generateSecret(dks);

        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, securekey);
        byte[] b = cipher.doFinal(src.getBytes("UTF-8"));

        String ss = new String(Base64.encodeBase64(b));
        ss = ss.replaceAll("\\+", "-");
        ss = ss.replaceAll("/", "_");
        return ss;
    } catch(Exception ex){
        ex.printStackTrace();
        return src;
    }
}

public static String decryptThreeDESECB(String src, String key) {
    try{
        src = src.replaceAll("-", "+");
        src = src.replaceAll("_", "/");
        byte[] bytesrc = Base64.decodeBase64(src.getBytes("UTF-8"));
        // --Decrypted key
        DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey securekey = keyFactory.generateSecret(dks);

        // --Cipher object decryption
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, securekey);
        byte[] retByte = cipher.doFinal(bytesrc);

        return new String(retByte, "UTF-8");
    } catch(Exception ex){
        ex.printStackTrace();
        return src;
    }
}

2.3 AES
AES advanced data encryption standard can effectively resist all known attacks against DES algorithm. The default key length is 128 bits, and 192 bits and 256 bits can be selected. By the way, this bit refers to bit.

private static final String defaultCharset = "UTF-8";
private static final String KEY_AES = "AES";
private static final String KEY_MD5 = "MD5";
private static MessageDigest md5Digest;
static {
    try {
        md5Digest = MessageDigest.getInstance(KEY_MD5);
    } catch (NoSuchAlgorithmException e) {

    }
}
/**
  * encryption
  */
public static String encrypt(String data, String key) {
    return doAES(data, key, Cipher.ENCRYPT_MODE);
}
/**
  * decrypt
  */
public static String decrypt(String data, String key) {
    return doAES(data, key, Cipher.DECRYPT_MODE);
}


/**
  * Encryption and decryption
  */
private static String doAES(String data, String key, int mode) {
    try {
        boolean encrypt = mode == Cipher.ENCRYPT_MODE;
        byte[] content;
        if (encrypt) {
            content = data.getBytes(defaultCharset);
        } else {
            content = Base64.decodeBase64(data.getBytes());
        }
        SecretKeySpec keySpec = new SecretKeySpec(md5Digest.digest(key.getBytes(defaultCharset))
                                                  , KEY_AES);
        Cipher cipher = Cipher.getInstance(KEY_AES);// Create cipher
        cipher.init(mode, keySpec);// initialization
        byte[] result = cipher.doFinal(content);
        if (encrypt) {
            return new String(Base64.encodeBase64(result));
        } else {
            return new String(result, defaultCharset);
        }
    } catch (Exception e) {
    }
    return null;
}

The recommended symmetric encryption algorithms are: AES128, AES192 and AES256.

3, Asymmetric encryption algorithm

Asymmetric encryption algorithm has two keys, which are completely different but completely matched. The encryption and decryption of plaintext can only be completed by using a matching pair of public and private keys. Common asymmetric encryption include RSA, SM2, etc.

3.1 RSA
The RSA key is at least 500 bits long, and 1024 bits are generally recommended.

//Asymmetric key algorithm
public static final String KEY_ALGORITHM = "RSA";

/**
  * Key length: the default key length of DH algorithm is 1024
  * The key length must be a multiple of 64, between 512 and 65536 bits
  */
private static final int KEY_SIZE = 1024;
//Public key
private static final String PUBLIC_KEY = "RSAPublicKey";
//Private key
private static final String PRIVATE_KEY = "RSAPrivateKey";
/**
  * Initialize key pair
  *
  * @return Map Map of Party A's key
  */
public static Map<String, Object> initKey() throws Exception {
    //Instantiate key generator
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    //Initialize key generator
    keyPairGenerator.initialize(KEY_SIZE);
    //Generate key pair
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    //Party A's public key
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    //Party A's private key
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    //Store key in map
    Map<String, Object> keyMap = new HashMap<String, Object>();
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
}
/**
  * Private key encryption
  *
  * @param data Data to be encrypted
  * @param key  secret key
  * @return byte[] Encrypted data
  */
public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception {

    //Get private key
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //Generate private key
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
    //data encryption 
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateKey);
    return cipher.doFinal(data);
}

/**
  * Public key encryption
  *
  * @param data Data to be encrypted
  * @param key  secret key
  * @return byte[] Encrypted data
  */
public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception {

    //Instantiate key factory
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //Initialize public key
    //Key material conversion
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
    //Generate public key
    PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
    //data encryption 
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    return cipher.doFinal(data);
}

/**
  * Private key decryption
  *
  * @param data Data to be decrypted
  * @param key  secret key
  * @return byte[] Decrypt data
  */
public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception {
    //Get private key
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //Generate private key
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
    //data decryption 
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return cipher.doFinal(data);
}

/**
  * Public key decryption
  *
  * @param data Data to be decrypted
  * @param key  secret key
  * @return byte[] Decrypt data
  */
public static byte[] decryptByPublicKey(byte[] data, byte[] key) throws Exception {

    //Instantiate key factory
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //Initialize public key
    //Key material conversion
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
    //Generate public key
    PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
    //data decryption 
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, pubKey);
    return cipher.doFinal(data);
}

/**
  * Get private key
  *
  * @param keyMap Key map
  * @return byte[] Private key
  */
public static byte[] getPrivateKey(Map<String, Object> keyMap) {
    Key key = (Key) keyMap.get(PRIVATE_KEY);
    return key.getEncoded();
}

/**
  * Get public key
  *
  * @param keyMap Key map
  * @return byte[] Public key
  */
public static byte[] getPublicKey(Map<String, Object> keyMap) throws Exception {
    Key key = (Key) keyMap.get(PUBLIC_KEY);
    return key.getEncoded();
}

4, Encryption salt

Encryption salt is also a commonly heard concept. Salt is a random string used for encryption after splicing with our encryption string. Salt is mainly used to provide the security of encrypted strings. If there is an encrypted string after adding salt, the plaintext obtained by the hacker through certain means is not the string before encryption, but the string before encryption and the string combined with salt, which relatively increases the security of the string.

The recommended encryption algorithms are:

  • Irreversible encryption: SHA256, SHA384, SHA512 and HMAC-SHA256, HMAC-SHA384, HMAC-SHA512
  • Symmetric encryption algorithm: AES, 3DES
  • Asymmetric encryption algorithm: RSA

Thank you for seeing here. I'm Maidong, a programmer and a java developer. I've been working in the industry for six years. I share Java related technical articles or industry information every day

Welcome to pay attention to and forward articles, and welfare gifts in the later stage!

Tags: Python Java Algorithm Encryption cryptology

Posted by Fearless_Fish on Tue, 24 May 2022 01:49:38 +0300