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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值