加密代码

 

        /**解密
* @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. Objective-C中的浅拷贝和深拷贝(转载)

    本文转自:http://segmentfault.com/blog/channe/1190000000604331 浅拷贝 浅拷贝就是对内存地址的复制,让目标对象指针和源对象指向同一片内存空间.如: ...

  2. Linux远程执行Shell命令或脚本

    ## 远程执行shell命令 ssh [user]@[server] '[command]' # eg. ssh root@192.168.1.1 'uptime' ## 远程执行本地shell脚本 ...

  3. WhatsApp的Erlang世界

    rick 的两个ppt整理 下载:2012 2013  ,使用半年erlang后,重新看这两个ppt才发现更多值的学习的地方,从ppt中整理如下: - Prefer os:timestamp to e ...

  4. js随机生成颜色代码

    function generyRandomColor() { return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toStri ...

  5. JSP复习整理(五)JavaBean使用表单处理数据

    一.先建立用户输入的数据 usingGetparameter.html <!DOCTYPE html> <html> <head> <meta charset ...

  6. 书柜的尺寸(bzoj 1933)

    Description Tom不喜欢那种一字长龙式的大书架,他只想要一个小书柜来存放他的系列工具书.Tom打算把书柜放在桌子的后面,这样需要查书的时候就可以不用起身离开了.显然,这种书柜不能太大,To ...

  7. mysql事务

    1. 事务并不专属于mysql 2. 事务的ACID特性 1)原子性(atomicity) 一个事务必须被视为一个不可分割的最小工作单元,整个事务中得所有操作要么全部提交成功,要么全部失败回滚,对于一 ...

  8. Android版本与api Level

    Platform Version API Level VERSION_CODE Notes Android 4.4 19 KITKAT Platform Highlights Android 4.3 ...

  9. LInux Shell 快捷键

    CTRL 键相关的快捷键: Ctrl + a - Jump to the start of the lineCtrl + b - Move back a charCtrl + c - Terminat ...

  10. Linux更改计算机名称

    1.修改:vim /etc/hosts 2.修改:vim /etc/sysconfig/network 3.重启:reboot 如不重启可以输入:hostname  新改的计算机名称,然后su