关于AES在Android和JAVA上加密解密不能对应的问题

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

在网上搜搜刮刮,整了一个工具类出来,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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值