Can someone help me with this code? I’m trying to encrypt and decrypt a message with RSA in the same program.
This is the code:
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)
I’m getting this error when I run it:
Traceback (most recent call last): [file], line 30, in <module> decrypted = decryptor.decrypt(ast.literal_eval(str(encrypted))) File "C:UsersuserAppDataLocalProgramsPythonPython312Libsite-packagesCryptoCipherPKCS1_OAEP.py", line 163, in decrypt modBits = Crypto.Util.number.size(self._key.n) AttributeError: 'bytes' object has no attribute 'n'
juan perez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.