1. 程式人生 > >java實現AES加解密

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