gpt4 book ai didi

python - RSA pycryptodome 解密不正确

转载 作者:行者123 更新时间:2023-12-01 08:51:20 26 4
gpt4 key购买 nike

我尝试使用 pycryptodome 在 Python 中实现 RSA,加密工作正常,但解密功能不行,我的代码如下:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import pss
from Crypto.Hash import SHA256

class RSA_OBJECT:


def create_KeyPair(self):

self.key = RSA.generate(self.KEY_LENGTH)


def save_PrivateKey(self, file, password):

key_cifrada = self.key.export_key(passphrase=password, pkcs=8,protection="scryptAndAES128-CBC")
file_out = open(file, "wb")
file_out.write(key_cifrada)
file_out.close()


def load_PrivateKey(self, file, password):
key_cifrada = open(file, "rb").read()
self.private_key = RSA.import_key(key_cifrada, passphrase=password)


def save_PublicKey(self, file):
key_pub = self.key.publickey().export_key()
file_out = open(file, "wb")
file_out.write(key_pub)
file_out.close()

def load_PublicKey(self, file):

key_publica = open(file, "rb").read()
self.public_key = RSA.import_key(key_publica)

我不知道为什么,因为我认为代码是正确的,有人可以帮助我吗?

最佳答案

你的问题是你生成了两个不同的 key ;

self.public_key = RSA.generate(self.KEY_LENGTH)
self.private_key = RSA.generate(self.KEY_LENGTH)

你应该;

key = RSA.generate(self.KEY_LENGTH)

private_key = key.export_key()
file_out = open("private.pem", "wb")
file_out.write(private_key)

public_key = key.publickey().export_key()
file_out = open("receiver.pem", "wb")
file_out.write(public_key)

参见here更多详细信息;

<小时/>

注意:请注意,由于公钥加密, key 对象具有两个功能。您可以将私钥写入一个文件,将公钥写入另一个文件。这样就可以分发 key 了。请参阅RSAKey .

关于python - RSA pycryptodome 解密不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53099241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com