RSA加密/解密脚本

问题描述 投票:0回答:1

有人可以帮我解决这个代码吗?我正在尝试在同一程序中使用 RSA 加密和解密消息。

这是代码:

import ast
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii
 
keyPair = RSA.generate(3072)
 
pubKey = keyPair.publickey()
print(f"Public key:  (n={hex(pubKey.n)}, e={hex(pubKey.e)})")
pubKeyPEM = pubKey.exportKey()
print(pubKeyPEM.decode('utf-8'))
 
print(f"Private key: (n={hex(pubKey.n)}, d={hex(keyPair.d)})")
privKeyPEM = keyPair.exportKey()
print(privKeyPEM.decode('utf-8'))
 
#encryption
msg = input("Enter message to encrypt: ")
msg = msg.encode()
encryptor = PKCS1_OAEP.new(pubKey)
encrypted = encryptor.encrypt(msg)
print("Encrypted (ciphertext): ", binascii.hexlify(encrypted))

print("=============")

print("=============")

#decryption
decryptor = PKCS1_OAEP.new(privKeyPEM)
decrypted = decryptor.decrypt(ast.literal_eval(str(encrypted)))
print("Plaintext (decrypted message):")
print(decrypted)

运行时出现此错误:

Traceback (most recent call last):
  [file], line 30, in <module>
    decrypted = decryptor.decrypt(ast.literal_eval(str(encrypted)))
  File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\Crypto\Cipher\PKCS1_OAEP.py", line 163, in decrypt
    modBits = Crypto.Util.number.size(self._key.n)
AttributeError: 'bytes' object has no attribute 'n'
python python-3.x encryption cryptography rsa
1个回答
0
投票

PKCS1_OAEP.new
方法将
RsaKey
作为第一个参数,但不是
bytes
。 从代码中提供
keyPair
而不是
keyPair.exportKey()
解决问题。

decryptor = PKCS1_OAEP.new(keyPair)
© www.soinside.com 2019 - 2024. All rights reserved.