【问题标题】:Using python M2Crypto AES cipher with java在 java 中使用 python M2Crypto AES 密码
【发布时间】:2013-09-16 12:10:48
【问题描述】:

我有以下 python 代码:

def AES_build_cipher(key, iv, op):
   return EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=op, padding=True) # PKCS#5 paddig

def AES_encrypt(key, msg, iv): # key, iv -> bytes, msg -> text
   if iv is None:
       raise ValueError("IV must be defined!")

  # Return the encryption function
   def encrypt(data):
       cipher = AES_build_cipher(key, iv, ENCRYPTION)
       v = cipher.update(data)
       v = v + cipher.final()
       del cipher
       return v

   return encrypt(msg)

它工作正常(通过 M2Crypto 加密/解密)。

用于解密的Java代码:

public static String AESDecrypt(String b64data, byte[] key, byte[] iv) throws CipherException {
    try {
        aesCipher_ = Cipher.getInstance("AES/CBC/PKCS5Padding");
        aesCipher_.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));

        final byte[] byteData = Base64.decode(b64data, Base64.DEFAULT);
        final byte[] decryptedData = aesCipher_.doFinal(byteData);

        return new String(decryptedData);
    } catch (Exception e) {
        throw new CipherException(e);
    }
}

数据:

  • iv = 8b9123ba6712612fb98452aac3854838(十六进制表示)
  • 文本 = 12345678901234567890(简单文本)
  • 密文= af87d97bf9779efcff0386d4eaee18619dc8f1fe7c5adea2a91657f53491bc2(十六进制 代表)
  • 密码 = 791a06ee369dc2f842c655f6bec8ce2(十六进制表示)

结果:

  • Exp:'12345678901234567890'
  • 得到:'1���$V��c�J�}7890'

看起来 IV 有问题(结果的前 16 个字节)。但我不知道我错过了什么。

【问题讨论】:

    标签: java python openssl aes m2crypto


    【解决方案1】:

    问题出在 python 中的 IV 上。它实际上是 unicode 字符串,而不是 ascii 字符串。 以下代码将帮助将 unicode str 转换为 ascii str:

    ''.join([chr(ord(x)) for x in request.session['iv']])
    

    【讨论】:

      猜你喜欢
      • 2018-09-07
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 2013-11-14
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多