在java项目中使用AES256 CBC加密

首先要注意一点,默认的JDK是不支持256位加密的,需要到Oracle官网下载加密增强文件(Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 8),否则编译会报错:

java.security.InvalidKeyException: Illegal key size

解压后替换jre/lib/security/目录下的同名文件即可。

最简单的应用实例:

public class IotServer {

    private static final byte[] key = {..};//key.length须满足16的整数倍
    private static final byte[] iv = {..};//iv.length须满足16的整数倍
    private static final String transform = "AES/CBC/PKCS5Padding";
    private static final String algorithm = "AES";
    private static final SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);

    public static void main(String[] args) {
        Cipher cipher = Cipher.getInstance(transform);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
        byte[] cipherData = cipher.doFinal("待加密的明文".getBytes("UTF-8"));
        System.out.println(Arrays.toString(cipherData));
    }

}

key和iv都可以通过更复杂的方式生成,方法很多这里不再列出,更多的使用技巧会在实际应用中发现。

posted @ 2015-07-12 18:49  Gugia桑  阅读(8492)  评论(0编辑  收藏  举报