V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
john990
V2EX  ›  问与答

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

  •  
  •   john990 · 2015-03-04 11:41:40 +08:00 · 4661 次点击
    这是一个创建于 3343 天前的主题,其中的信息可能已经有所发展或是发生改变。

    不管是 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;
    }
    
    两种语言自己加密解密都是正常的
    
    5 条回复    2015-03-04 23:18:50 +08:00
    hao123yinlong
        1
    hao123yinlong  
       2015-03-04 13:49:09 +08:00   ❤️ 1
    看看是否是字符编码造成
    john990
        2
    john990  
    OP
       2015-03-04 15:08:45 +08:00
    @hao123yinlong 两边都是UTF-8编码,而且除了前几个字节其他部分都能正常解密
    juntao
        3
    juntao  
       2015-03-04 15:17:14 +08:00   ❤️ 1
    两边的IV一样吗?我遇到过IV不一致的情况会有这种表现。
    john990
        4
    john990  
    OP
       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
        5
    juntao  
       2015-03-04 23:18:50 +08:00
    @john990
    1、你把IV都设置成 '\0'*8 试试不就知道了吗。
    2、按你的方式,只要你加解密之间超过1毫秒,iv肯定就不同咯。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1208 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 23:23 · PVG 07:23 · LAX 16:23 · JFK 19:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.