【发布时间】:2021-10-05 22:39:46
【问题描述】:
我正在编写 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 值(样本值):
InKey = “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 中是否有任何其他方法来处理?
谢谢。
【问题讨论】:
-
这些值是 base64 编码的,没有明智的方法从 686 个字符的 base64 编码字节中获取 16 或 32 个字节。也许这些是使用 4096 位 RSA 模数的 RSA 加密的结果,但即便如此,我也希望是 684 个字符,而不是 686。也没有理由加密 IV。您将不得不从您的“客户团队”那里找到更多详细信息,实际上没有 Java generic 加密示例这样的东西。
-
感谢詹姆斯的回复。是的,你是对的,它是 684 个字符,是由 4096 位模数的 RSA 加密产生的。现在我们正在寻找一种方法来从 base64 编码的 684 个字符中获取预期的 16 字节大小的 IV 和密钥。
-
如果我们能看到加密代码会有所帮助。
-
感谢@bereal 对此进行调查。是的,现在我在帖子中更新了更多细节。如果您可以在此处提供任何输入,请您帮忙检查并告诉我。仅供参考-我们没有加密代码,我们只处理解密逻辑。
-
@bereal 如果您对此问题的解决方案有任何意见,请告诉我们。
标签: encryption aes initialization-vector