java实现AES加解密

在数据的传输过程中,对于敏感的数据通常会进行加密操作。下面是AES对敏感数据加密的实现。
1.代码:
public class AesTest {


    private final static String algorithm = "AES/CBC/PKCS5Padding";// AES/ECB/PKCS5Padding不需要IVParams
    //必须是16位
    private final static String ivParams = "9615932213231253";


    public static void main(String[] args) {
        String data = "13347255915";
        //aes秘钥有长度限制(16位)
        String aesKey = getAesKey();
        try {
            //加密
            byte[] bytes = encryptOrDecrypt(data.getBytes("utf-8"), aesKey, Cipher.ENCRYPT_MODE, algorithm, ivParams);
            String encrypt = Base64Util.encrypt(bytes);
            System.out.println("加密后的数据是:" + encrypt);
            //解密
            byte[] bytes1 = encryptOrDecrypt(Base64Util.decrypt(encrypt), aesKey, Cipher.DECRYPT_MODE,
                    algorithm, ivParams);
            System.out.println("解密后的数据是:" + new String(bytes1));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static byte[] encryptOrDecrypt(byte[] data, String aesKey, int mode, String algorithm, String ivParams)
            throws Exception {
        Provider provider = new BouncyCastleProvider();
        SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey.getBytes("utf-8"), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivParams.getBytes("utf-8"));
        Cipher cipher = Cipher.getInstance(algorithm, provider);
        cipher.init(mode, secretKeySpec, ivParameterSpec);
        byte[] bytes = cipher.doFinal(data);
        return bytes;
    }


    public static String getAesKey() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 16; i++) {
            int v = (int)(Math.random() * 9);
            sb.append(v);
        }
        return sb.toString();
    }
}


BASE64工具类:
public class Base64Util {


    public static String encrypt(byte[] data){
        return new String(Base64.encode(data));
    }


    public static byte[] decrypt(String data){
        try {
            return Base64.decode(data.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
2.如果想要aes秘钥不受限制,如24位,32位。参考如下链接:
http://blog.csdn.net/gf771115/article/details/53817658

你可能感兴趣的:(java实现AES加解密)