【问题标题】:RSA cipher incompatibility - python script cannot decrypt a key encrypted by a bash scriptRSA 密码不兼容 - python 脚本无法解密由 bash 脚本加密的密钥
【发布时间】:2019-06-28 21:58:20
【问题描述】:

我写了一个实现加密和解密的python脚本。为了向接收方发送加密数据的密钥,程序使用 RSA 公钥加密和解密随机生成的密钥。

下面是我用来加密和解密公钥/私钥的python脚本中的加密和解密方法:

from Crypto.Cipher import PKCS1_OAEP

def encrypt_public_key(msg, public_key):
    cipher = PKCS1_OAEP.new(public_key)
    return cipher.encrypt(msg)

def decrypt_private_key(msg, private_key):
    cipher = PKCS1_OAEP.new(private_key)
    return cipher.decrypt(msg)

我的程序应该和一个同学的程序通信,但是,这个人已经将他的程序写成一个 bash 脚本,使用以下命令进行加密和解密:

openssl rsautl -encrypt -inkey id_rsa.pub.pem -pubin -in key.bin -out key.bin.enc
openssl rsautl -decrypt -inkey id_rsa.pem -in key.bin.enc -out key.bin 

当我的程序尝试解密我的同学加密密钥时,我收到此错误:

File "[script-path]", line 54, in decrypt_private_key
return cipher.decrypt(msg)
File "C:\[path_to_python]\Python37-32\lib\site-packages\Crypto\Cipher\PKCS1_OAEP.py", line 167, in decrypt
    raise ValueError("Ciphertext with incorrect length.")
ValueError: Ciphertext with incorrect length.

我相信这意味着我们的脚本没有使用相同的密码,我对这个假设是否正确?但是,我找不到用于 bash 脚本的密码(我的同学也不知道),我正在努力寻找如何在 python Crypto 模块中使用另一种密码。

我尝试将我的加密和解密方法切换为类似的方法:

from Crypto.PublicKey import RSA

def encrypt_public_key(msg, public_key):
    return public_key.encrypt(msg, 32)
def decrypt_private_key(msg, private_key):
    return private_key.decrypt(msg)

但这给了我以下错误:

File "[script_path]", line 52, in decrypt_private_key
    return private_key.decrypt(msg)
  File "[python-path]\Python37-32\lib\site-packages\Crypto\PublicKey\RSA.py", line 378, in decrypt
    raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead")
NotImplementedError: Use module Crypto.Cipher.PKCS1_OAEP instead

哪个密码 (PKCS1_OAEP) 不能使用我同学的加密密钥。

您对我能做些什么来解决这个问题有什么建议吗?问题是我们使用不同的密码吗?有没有办法切换我的密码,还是我必须从我的 python Crypto 模块切换?

【问题讨论】:

  • 不要使用 PyCrypto。使用密码学。 PyCrypto 已经 6 年没有更新了。不是您问题的解决方案,只是评论。

标签: python encryption openssl rsa pycrypto


【解决方案1】:

您可能正在使用不同的 RSA 填充方案。 也许你的同学可以尝试使用rsautl OAEP 填充选项-oaep

openssl rsautl 的默认填充模式似乎是 -pkcs (PKCS#1 v1.5)。

因此,您也可以尝试使用:

from Crypto.Cipher import PKCS1_v1_5

【讨论】:

  • 我现在按照本指南将我的 OAEP 切换到 PKCS1_v1_5:link。但是我在尝试使用cipher.decrypt(msg, sentinel) 解密时收到错误AttributeError: 'PKCS115_SigScheme' object has no attribute 'decrypt'。我查看了 PKCS1_v1_5 的源代码,它具有解密方法。你知道为什么会这样吗?
猜你喜欢
  • 1970-01-01
  • 2012-05-08
  • 2014-12-08
  • 2014-10-28
  • 2018-12-30
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
相关资源
最近更新 更多