Python AES 解密初始化向量和密钥值大小问题

问题描述

我正在编写 Python 解密逻辑来解密消息(客户端使用 Java 加密)。 Python代码

 def decrypt(self,text):        
            decode = base64.b64decode(text)
            cryptor = AES.new(InKey,MODE_CBC,InIV)
            plain_text = cryptor.decrypt(decode)
            return unpad(plain_text) 
    

我从客户团队收到以下关键和 IV 值(样本值):

输入键 = “6asd6587daIs8g2qvi3rJbM9sdasd6cb2kdYC0TOy5zEgTo+8LrQn0UJZAmJCtmX......”(它 是 684 个字符的长度)InIV = “7as76cascsagoKtID7z1nUakJqzj+Dwl9cL9Q2/zBFbs0Sg3Kw6US8yvvzbkyg2bnjGHWofIWrhMQ/Bcde....” (它是684个字符的长度)

问题:运行上述python代码时,出现以下错误。如何将上面的IV值转换成16bytes大小和key-value长度?

ValueError:IV 长度不正确(必须是 16 个字节)

现有的解密 Java 客户端遵循混合模式(首先使用 RSA 私钥提取两个参数(IV 和密钥)...然后使用 AES 密码解密实际消息):

代码

................................
//Step-1) Generate RSA-PrivateKey
................................
RSAPrivateKey serverPrivateKey = KeyUtils.getPrivateKey("lib",PrivKey); 
/* here PrivKey refers to .der certificate 
   and FYI- KeyUtils actually refers to a class,that generate RSA PrivateKey with below code:      
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                KeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);
            return (RSAPrivateKey)keyFactory.generatePrivate(ks);
*/
................................
//Step-2) use RSA-PrivateKey to decrypt the message
................................
MessageEncryption encryptor = new MessageEncryption(serverPrivateKey); 
/* initializes Cipher(RSA instance) with passed RSA PrivateKey 
 this.m_asymmetricalKey = serverPrivateKey;
 this.m_asymmetricalCipher = Cipher.getInstance(this.m_asymmetricalKey.getAlgorithm());
*/

encryptor.decryptMessage(JSONresponseBody);  // invokes below mentioned method
...............
decryptMessage(JSONObject jsonMessage)
{
    .............................
    IvParameterSpec initializationVector = new IvParameterSpec(this.m_asymmetricalCipher.doFinal(StringCodec.decodeBase64(jsonMessage.getString("iv").getBytes())));     
    this.m_asymmetricalCipher.init(2,this.m_asymmetricalKey);          
    Key secretKey = new SecretKeySpec(this.m_asymmetricalCipher.doFinal(StringCodec.decodeBase64(jsonMessage.getString("key").getBytes())),"AES");
    Cipher symmetricalCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    symmetricalCipher.init(2,secretKey,initializationVector);
    return new String(symmetricalCipher.doFinal(StringCodec.decodeBase64(jsonMessage.getString("message").getBytes())));
    .............................   

}
..............

那么在 Python 中如何获得正确的键大小和 IV,有没有办法在 Java 中实现类似的混合模式,或者是否有其他方法可以在 Python 中处理?

谢谢。

解决方法

您的 Java 端代码执行以下操作:

  1. 读取 PKCS8 编码的 RSA 密钥
  2. 解码 base64 编码的 IV
  3. 使用私钥解密 IV(旁注:加密 IV 对我来说意义不大)
  4. 解码 base64 编码的 AES 密钥
  5. 使用私钥解密 AES 密钥
  6. 解码 base64 编码的密文
  7. 使用获得的IV和AES密钥解密密文

您需要在 Python 中重新实现上述每个步骤。有些是微不足道的,比如 base64 解码。其他取决于您使用的加密库。