Java 和 python DES3 加密 转换,总是前几个字节解不出来?

2015-03-04 11:41:40 +08:00
 john990

不管是 python 加密 -> java 解密,或 java加密->python解密 总是有前几个字节(3-8个不定)解不出来,难道是我操作方式不对?
python 加密代码:
python
def encrypt(content):
iv_time = long(time.time() * 1000)
iv = struct.pack('Q', iv_time)
des = DES3.new(http_api_app_secret, DES3.MODE_CBC, iv)
content = encrypt_pad(content)
content = des.encrypt(content)
content = urllib.quote(base64.b64encode(content))
return str(iv_time) + content

java 解密代码:
`````

byte[] decrypt(byte[] key, byte[] iv, byte[] message) {
    byte[] result = null;
    try {
        Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
        SecretKey secretKey = skf.generateSecret(new DESedeKeySpec(key));
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

        result = cipher.doFinal(message);
    } catch (Exception e) {
        throw new SecurityException(e);
    }

    return result;
}
两种语言自己加密解密都是正常的
4672 次点击
所在节点    问与答
5 条回复
hao123yinlong
2015-03-04 13:49:09 +08:00
看看是否是字符编码造成
john990
2015-03-04 15:08:45 +08:00
@hao123yinlong 两边都是UTF-8编码,而且除了前几个字节其他部分都能正常解密
juntao
2015-03-04 15:17:14 +08:00
两边的IV一样吗?我遇到过IV不一致的情况会有这种表现。
john990
2015-03-04 15:27:07 +08:00
@juntao 对,这好像有点问题,不知道这两种方法是不是等价的:
python中是这样:13位long型时间戳
iv_time = long(time.time() * 1000)
iv = struct.pack('Q', iv_time)

java中得到iv_time
ByteBuffer byteBuffer = ByteBuffer.allocate(8);
byteBuffer.order(ByteOrder.BIG_ENDIAN);
byteBuffer.putLong(v);
取8位字节数组
juntao
2015-03-04 23:18:50 +08:00
@john990
1、你把IV都设置成 '\0'*8 试试不就知道了吗。
2、按你的方式,只要你加解密之间超过1毫秒,iv肯定就不同咯。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/174359

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX