- Foundations of Blockchain
- Koshik Raj
- 190字
- 2021-07-02 14:17:12
An example implementation of RSA
The example uses the RSA packages in the Python PyCryptodome library. The following packages are imported for RSA key generation and the encryption and decryption operations:
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP
A 2048-bit RSA key is created using the generate method from the RSA package. The public key is exported from this generated key and made public. The key object should be kept secret. A cipher object is created using the public key, and encryption is performed on the message using this object:
message = "plaintext for RSA" key = RSA.generate(2048) public = key.publickey() cipher = PKCS1_OAEP.new(public) cipher_text = cipher.encrypt(message.encode())
print("Data is encrypted")
The decryption operation is performed in a similar way to the encryption operation, but the private part of the key pair is used instead of the public part. The ciphertext is given as input to the decrypt method, which decrypts it and gives back the decrypted message:
cipher = PKCS1_OAEP.new(key) message = cipher.decrypt(cipher_text) print("Decrypted data is : \"{}\"".format(message.decode()))
A successful execution of the preceding script will output the following:
Data is encrypted
Decrypted data is : "plaintext for RSA"