加密代码

 

        /**解密
* @param content 待解密内容
* @param password 解密密钥
* @return
*/
public static byte[] decrypt(byte[] content, String password) {
try {
KeyGenerator 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 e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}

  

 

解密代码

        /**解密
* @param content 待解密内容
* @param password 解密密钥
* @return
*/
public static byte[] decrypt(byte[] content, String password) {
try {
KeyGenerator 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 e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}

  

解密代码

                String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
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();
}

  

偶尔会报错 抛出异常,

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
 
原因  加密后的byte数组是不能强制转换成字符串的,换言之:字符串和byte数组在这种情况下不是互逆的;要避免这种情况,我们需要做一些修订,可以考虑将二进制数据转换成十六进制表示
解决方案 
 

二进制转换成16进制

        /**将16进制转换为二进制
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}

  

16进制转换为二进制

测试结果,问题解决

                String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("加密后:" + encryptResultStr);
//解密
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom,password);
System.out.println("解密后:" + new String(decryptResult));

  

测试结果如下:
加密前:test
加密后:73C58BAFE578C59366D8C995CD0B9D6D
解密后:test
 
 
 

JAVA实现AES 解密报错Input length must be multiple of 16 when decrypting with padded cipher的更多相关文章

  1. java对称加密报错:Input length must be multiple of 8 when decrypting with padded cipher

    HTTP Status 500 - Request processing failed; nested exception is javax.crypto.IllegalBlockSizeExcept ...

  2. url请求时,参数中的+在服务器接收时为空格,导致AES加密报出javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher

    报错的意思的是使用该种解密方式出入长度应为16bit的倍数,但实际的错误却不是这个,错误原因根本上是因为在http请求是特殊字符编码错误,具体就是base64生成的+号,服务器接收时成了空格,然后导致 ...

  3. javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher--转载

    原文地址:http://songjianyong.iteye.com/blog/1571029 /** * AESHelper.java * cn.com.songjy.test * * Functi ...

  4. 我的Android进阶之旅------>解决AES加密报错:java.security.InvalidKeyException: Unsupported key size: 18 bytes

    1.错误描述 今天使用AES进行加密时候,报错如下所示: 04-21 11:08:18.087 27501-27501/com.xtc.watch E/AESUtil.decryptAES:55: j ...

  5. RSA解密报错java.security.spec.InvalidKeySpecException的解决办法

    java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid p ...

  6. Android AES加密报错处理:javax.crypto.IllegalBlockSizeException: error:1e00007b:Cipher functions:OPENSSL_internal:WRONG_FINAL_BLOCK_LENGTH

    一.问题说明 今天写AES加/解密功能的apk,设想是四个控件(测试用的,界面丑这种东西请忽略) 一个编缉框----用于输入要加密的字符串 一个文本框----用于输出加密后的字符串,和加密后点击解密按 ...

  7. SRA解密报错:Data must start with zero

    项目背景:要对打印地址进行加密,用公钥加密后会乱码需要base64 decode一下,但是在解密时报错:javax.crypto.BadPaddingException: Data must star ...

  8. 微信第三方平台解密报错:Illegal key size

    今天在交接别人代码的时候遇到的,微信第三方平台解密报的错误,原因: 如果密钥大于128, 会抛出java.security.InvalidKeyException: Illegal key size ...

  9. Java基础学习总结(35)——Java正则表达式详解

    在Sun的Java JDK 1.40版本中,Java自带了支持正则表达式的包,本文就抛砖引玉地介绍了如何使用java.util.regex包. 可粗略估计一下,除了偶尔用Linux的外,其他Linu  ...

随机推荐

  1. MAC OS PHP

    Apache与PHP的配置 OSX自带了apache和php,但默认情况下没有开启,打开终端 sudo apachectl start 这时在浏览器中输入localhost应该就会出现apache标准 ...

  2. Visual Studio Emulator for Android 的安装与使用 感觉最干净好看的模拟器.

    Step1 win8+ 6G+ 添加删除程序\ hyper  创建虚拟机 安装visual studio android 模拟器, 自带三个模拟器 使用管理员打开模拟器 参考文献 Visual Stu ...

  3. LeetCode 64 Minimum Path Sum

    Problem: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom ri ...

  4. Flask 框架入门

    Flask Flask是一个使用 Python 编写的轻量级 Web 应用框架.其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 . 安装 Flask 依赖两个外部库, We ...

  5. APP产品交互设计分析总结(不断更新中...)

    1.首页中的最下方的TAB和中部的TAB的区别 最下面的tab按钮应该是核心级模块级的大功能入口 中间的按钮应该是次核心级页面级的小功能入口 2.对于编辑是在单页内实现好还是跳转到新页面实现好 内容比 ...

  6. oracle对/dev/shm的使用

    查看共享内存打开的文件数 [root@db2 ~]# lsof -n | grep /dev/shm | wc -l 34693 共享内存中总共文件数 [root@db2 ~]# ls -l /dev ...

  7. Java中的private protected public和default的区别

    转至:http://blog.sina.com.cn/s/blog_74c571240101jaf5.html    类内部  本包  子类 外部包  public    √  √  √  √ pro ...

  8. Javascript、Jquery获取浏览器和屏幕各种高度宽度

    Javascript: IE中:document.body.clientWidth ==> BODY对象宽度document.body.clientHeight ==> BODY对象高度d ...

  9. Leetcode: Palindrome Partitioning II

    参考:http://www.cppblog.com/wicbnu/archive/2013/03/18/198565.html 我太喜欢用dfs和回溯法了,但是这些暴力的方法加上剪枝之后复杂度依然是很 ...

  10. Hibernate jpa 在实体类中对于时间的注解

    在时间类型DATE 属性上添加一个 @Temporal(TemporalType.DATE)(精确到年月日)@Temporal(TemporalType.TIME)(精确到时分秒)@Temporal( ...