博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AES加密算法的JAVA实现
阅读量:7230 次
发布时间:2019-06-29

本文共 5504 字,大约阅读时间需要 18 分钟。

最近公司需要,看了看AES对称加密算法,具体原理没有仔细研究还,先说说用法吧,由于能力有限,不足之处请大家多多指教,好了,不说废话了,直接上代码

/** * 加密 * * @param content  需要加密的内容 * @param password 加密密码 * @return */public static byte[] encrypt(String content, String password) {    KeyGenerator kgen = null;    try {        kgen = KeyGenerator.getInstance("AES");        kgen.init(128, new SecureRandom(password.getBytes()));        SecretKey secretKey = kgen.generateKey();        byte[] enCodeFormat = secretKey.getEncoded();        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");        Cipher cipher = Cipher.getInstance("AES");// 创建密码器        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化        byte[] byteContent = content.getBytes("utf-8");        byte[] result = cipher.doFinal(byteContent);        return result;//加密    } catch (NoSuchAlgorithmException | InvalidKeyException            | NoSuchPaddingException | BadPaddingException            | UnsupportedEncodingException | IllegalBlockSizeException e) {        e.printStackTrace();    }    return null;}/** * 解密 * * @param content  待解密内容 * @param password 解密密钥 * @return */public static byte[] decrypt(byte[] content, String password) {    KeyGenerator kgen = null;    try {        kgen = KeyGenerator.getInstance("AES");        kgen.init(128, new SecureRandom(password.getBytes()));        SecretKey secretKey = kgen.generateKey();        byte[] enCodeFormat = secretKey.getEncoded();        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");        Cipher cipher = Cipher.getInstance("AES");// 创建密码器        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化        byte[] result = cipher.doFinal(content);        return result; // 解密    } catch (NoSuchAlgorithmException | BadPaddingException            | IllegalBlockSizeException | NoSuchPaddingException            | InvalidKeyException e) {        e.printStackTrace();    }    return null;}
我们测试一下效果:
String content = "test";String password = "123456";//加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);System.out.println("加密后:" + encryptResult.toString());//解密byte[] decryptResult = decrypt(encryptResult, password);System.out.println("解密后:" + new String(decryptResult));

但有一点一定要注意——加密后的byte数组是不能强制转换成字符串的,我们可以实验下:
//解密try {    String encryptResultStr = new String(encryptResult, "utf-8");    byte[] decryptResult = decrypt(encryptResultStr.getBytes("utf-8"), password);    System.out.println("解密后:" + new String(decryptResult));} catch (UnsupportedEncodingException e) {    e.printStackTrace();}
运行后,会报如下错误:

具体原因我们就不再详细解释了,事实上这种方法也是没有实际意义的,因为我们要考虑java的跨平台特性,因此我们使用这句:
kgen.init(128, new SecureRandom(password.getBytes()));
生成随机密钥,在别的平台很可能获得的密钥是不相同的,所以这只里能当做展示罢了。
网上看了很多文章,发现还是这样写合适:
/** * 加密 * @param content * @param strKey * @return * @throws Exception */public static byte[] encrypt(String content,String strKey ) throws Exception {    SecretKeySpec skeySpec = getKey(strKey);    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");    IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);    byte[] encrypted = cipher.doFinal(content.getBytes());    return  encrypted;}/** * 解密 * @param strKey * @param content * @return * @throws Exception */public static String decrypt(byte[] content,String strKey ) throws Exception {    SecretKeySpec skeySpec = getKey(strKey);    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");    IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());    cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);    byte[] original = cipher.doFinal(content);    String originalString = new String(original);    return originalString;}private static SecretKeySpec getKey(String strKey) throws Exception {    byte[] arrBTmp = strKey.getBytes();    byte[] arrB = new byte[16]; // 创建一个空的16位字节数组(默认值为0)    for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {        arrB[i] = arrBTmp[i];    }    SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");    return skeySpec;}
测试就不写了,我们再对版本功能进行一下加强,对传输的数据使用base64进行编码,先写base64的编码和解码:
/** * base 64 encode * @param bytes 待编码的byte[] * @return 编码后的base 64 code */public static String base64Encode(byte[] bytes){    return new BASE64Encoder().encode(bytes);}/** * base 64 decode * @param base64Code 待解码的base 64 code * @return 解码后的byte[] * @throws Exception */public static byte[] base64Decode(String base64Code) throws Exception{    return base64Code.isEmpty() ? null : new BASE64Decoder().decodeBuffer(base64Code);}
接着对AES加密的数据进行base64编码,对AES解密的数据进行解码:
/** * AES加密为base 64 code * @param content 待加密的内容 * @param encryptKey 加密密钥 * @return 加密后的base 64 code * @throws Exception */public static String aesEncrypt(String content, String encryptKey) throws Exception {    return base64Encode(encrypt(content, encryptKey));}/** * 将base 64 code AES解密 * @param encryptStr 待解密的base 64 code * @param decryptKey 解密密钥 * @return 解密后的string * @throws Exception */public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {    return encryptStr.isEmpty() ? null : decrypt(base64Decode(encryptStr), decryptKey);}
写一个测试,看下效果:
public static void main(String[] args) throws Exception {    String test = "我爱你";    System.out.println("加密前:" + test);    String key = "123456";    System.out.println("密钥:" + key);    String encrypt = aesEncrypt(test, key);    System.out.println("加密后:" + encrypt);    String decrypt = aesDecrypt(encrypt, key);    System.out.println("解密后:" + decrypt);}
好了,受个人水平所限,就先写这么多吧,以后有更多内容再往上补充
参考:

你可能感兴趣的文章
linux dd 读取 写入磁盘速度
查看>>
dmidecode查看linux硬件信息
查看>>
linux监控对象及重要性
查看>>
walle-web自动化部署配置
查看>>
opencv轮廓提取、轮廓识别相关要点
查看>>
BOOST.ASIO源码剖析(一)
查看>>
过滤squidlog中各个链接的大小
查看>>
我的友情链接
查看>>
使用AnyChat如何实现任意两用户之间的音视频交互
查看>>
【个人小结】项目公共js的配置,解决不同页面多个配置修改的问题
查看>>
XAMP安装Apacher无法启动
查看>>
mongodb user
查看>>
ip地址子网划分
查看>>
Linux下快速搭建ntp时间同步服务器
查看>>
TouchEvent的传递过程学习笔记
查看>>
Android笔记--TCP Scoket(字符串收发)
查看>>
我的友情链接
查看>>
Hunt framework 2.0.0 发布,简单且高性能的 Web 服务框架
查看>>
数据库原理及应用(SQL Server 2016数据处理)【上海精品视频课程】
查看>>
MaxCompute表设计最佳实践
查看>>