JAVA AES algorithm encryption and decryption

The following is the AES algorithm implemented by JAVA in CBC mode PKCS5Padding encryption and decryption
1, encryption

    public static byte[] encrypt(byte[] sSrc,byte[] sKey,byte[] sIv) throws Exception {
        SecretKeySpec sKeySpec = new SecretKeySpec(sKey, "AES");
        //配置算法为AES、CBC模式、PKCS5Padding补码
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //使用CBC模式,需要一个向量iv
        IvParameterSpec iv = new IvParameterSpec(sIv);
        cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, iv);
        return cipher.doFinal(sSrc);
    }

2. Decryption

    public static byte[] decrypt(byte[] sSrc, byte[] sKey, byte[] sIv) throws Exception {
        SecretKeySpec sKeySpec = new SecretKeySpec(sKey, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //使用CBC模式,需要一个向量iv
        IvParameterSpec iv = new IvParameterSpec(sIv);
        cipher.init(Cipher.DECRYPT_MODE, sKeySpec, iv);
        return cipher.doFinal(sSrc);
    }

3. The following dependency packages belong to javase and do not need to be imported

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

4. The ECB mode is the same, one less IV vector is set than the CBC mode

Guess you like

Origin blog.csdn.net/zhangfls/article/details/108826358