john990
V2EX  ›  问与答

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

  •  
  •   john990 · Mar 4, 2015 · 5264 views
    This topic created in 4098 days ago, the information mentioned may be changed or developed.

    不管是 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 replies    2015-03-04 23:18:50 +08:00
    hao123yinlong
        1
    hao123yinlong  
       Mar 4, 2015   ❤️ 1
    看看是否是字符编码造成
    john990
        2
    john990  
    OP
       Mar 4, 2015
    @hao123yinlong 两边都是UTF-8编码,而且除了前几个字节其他部分都能正常解密
    juntao
        3
    juntao  
       Mar 4, 2015   ❤️ 1
    两边的IV一样吗?我遇到过IV不一致的情况会有这种表现。
    john990
        4
    john990  
    OP
       Mar 4, 2015
    @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  
       Mar 4, 2015
    @john990
    1、你把IV都设置成 '\0'*8 试试不就知道了吗。
    2、按你的方式,只要你加解密之间超过1毫秒,iv肯定就不同咯。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2851 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 14:54 · PVG 22:54 · LAX 07:54 · JFK 10:54
    ♥ Do have faith in what you're doing.