java中AES加密算法128位CBC模式工具类的实现—基于base64

这篇是基于base64实现的AES128加密算法,如果觉得base64没什么必要,可以看我下一篇没有base64的AES128加密算法博文

工具类:

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

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * AES加密128位CBC模式工具类
 */
public class AESUtils {

    //加密
    public static String Encrypt(String content, String IV, String KEY) throws Exception {
        byte[] raw = KEY.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
        //使用CBC模式,需要一个向量iv,可增加加密算法的强度
        IvParameterSpec ips = new IvParameterSpec(IV.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips);
        byte[] encrypted = cipher.doFinal(content.getBytes());
        return new BASE64Encoder().encode(encrypted);
    }

    //解密
    public static String Decrypt(String content, String KEY, String IV) throws Exception {
        try {
            byte[] raw = KEY.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(content);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

}

 Main方法测试:

public class DecodeTest {
    public static void main(String[] args) throws Exception {

        String a = "a nice body";

        //abcdefertyuiojgr是密钥,MAAAYAAAAAAAAABg是iv
        String encrypt = AESUtils.Encrypt(a, "abcdefertyuiojgr", "MAAAYAAAAAAAAABg");

         String b = AESUtils.Decrypt(encrypt, "abcdefertyuiojgr", "MAAAYAAAAAAAAABg");

        System.out.println(b);
        
    
    }
}

 

你可能感兴趣的:(java中AES加密算法128位CBC模式工具类的实现—基于base64)