首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

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

2013-10-30 
关于AES在Android和JAVA上加密解密不能对应的问题项目需要,客户端在提交信息的时候参数都需要加密传输在网

关于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]

热点排行