项目需要,客户端在提交信息的时候参数都需要加密传输

在网上搜搜刮刮,整了一个工具类出来,JAVA服务端总是解析报错,如下的异常



java.security.InvalidKeyException: Invalid AES key length: 6 bytes


仔细排查了一番


The problem is surely with the length of the key, I have tried different length but I am getting the same, could you please tell me the length of the key please, I am new to cryptography, I have made some research but still can't figure out the problem. Thanks a lot for your answers.


AES supports 128, 192 and 256 bit keys, so the number of bytes needs to be 16, 24, or 32. Note that the latter two may not be available in all circumstances (as the comment in the "kgen.init(128)" line mentions).


发现key的字节数必须是8的整数倍..修改key的长度。

加密解密的代码如下:


public static byte[] iv = {1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8};
//初始化向量参数,AES 为16bytes. DES 为8bytes.
public static String encrypt4AES(String source) {
try {

IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key1 = new SecretKeySpec(iv, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key1, zeroIv);
byte[] encryptedData = cipher.doFinal(source.getBytes());
String encryptResultStr = parseByte2HexStr(encryptedData);
return encryptResultStr; // 加密
} catch (Exception e) {
e.printStackTrace();
return "";
}
}

public static String decrypt4AES(String content) {
try {
byte[] decryptFrom = parseHexStr2Byte(content);

IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key1 = new SecretKeySpec(iv, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key1, zeroIv);
byte decryptedData[] = cipher.doFinal(decryptFrom);
return new String(decryptedData); // 加密
} catch (Exception e) {
e.printStackTrace();
return "";
}
}




CBC是工作模式,DES一共有电子密码本模式(ECB)、加密分组链接模式(CBC)、加密反馈模式(CFB)和输出反馈模式(OFB)四种模式,

PKCS5Padding是填充模式,还有其它的填充模式:

然后,cipher.init()一共有三个参数:Cipher.ENCRYPT_MODE, key, zeroIv,zeroIv就是初始化向量。

Android客户端加密后的内容,在JAVA端可以正常解密


[url]
http://www.cnblogs.com/lianghui66/archive/2013/03/07/2948494.html
[/url]

更多相关文章

  1. android将ROM改为默认开启调试模式和未知源,默认关闭GPS
  2. 命令模式与Android(安卓)Handler的工作原理
  3. Android:如何将位置信息模式默认设置为高精确度
  4. 简单模拟Android中AlertDialog的Builder设计模式
  5. 【Android】LitePal安装和使用
  6. Python 通过脚本获取Android的apk的部分属性,再通过加密算法生成
  7. JobIntentService与IntentService的区别
  8. android中基本的加密方法
  9. 【Android(安卓)开发教程】设置Activity的方向

随机推荐

  1. Android(安卓)- 主要的UI元素。
  2. 利用 RDP Wrapper 实现 Android(安卓)平
  3. Android随笔之——Android时间、日期相关
  4. Android获取外置SD卡读写路径
  5. Android(安卓)adb 我的常用调试命令记录(
  6. Android系统源码目录解析
  7. Android(安卓)Studio 中关于NDK编译及jni
  8. 开机提示“Android正在升级...”
  9. Android(安卓)Weak Handler:可以避免内存
  10. Android软键盘处理开发规范