Python RSA Encryption And Decryption Example
The cryptographic technique known as Rivest-Shamir-Adleman, or RSA, is used for certain security services or goals. It allows for public-key encryption and is frequently used to protect sensitive data, especially when it's being transferred over an unreliable network like the HTTP. Whereas a private key is confidential and needs to be kept to yourself, a public key is shared with others.
The following illustration highlights how asymmetric cryptography works:
Example: RSA Encryption and Decryption with RSA-OAEP Padding
from Crypto.PublicKey import RSAfrom Crypto.Cipher import PKCS1_OAEPimport base64
# 2048 is the number of bits for RSAkeys = RSA.generate(2048)
publicKey = keys.publickey()publicKeyPEM = publicKey.exportKey()print("\n",publicKeyPEM.decode('ascii'))
privateKeyPEM = keys.exportKey()print("\n",privateKeyPEM.decode('ascii'))
# Your secret textsecretMessage = 'This is your secret'
#encrypt the message with the RSA public keyencryptor = PKCS1_OAEP.new(publicKey)encrypted = encryptor.encrypt(secretMessage.encode())print("\nEncrypted:", base64.b64encode(encrypted).decode('ascii'))
#decrypt the message with the RSA private keydecryptor = PKCS1_OAEP.new(keys)decrypted = decryptor.decrypt(encrypted)print('\nDecrypted Message:', decrypted)
Console output:
-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3+v1KRkLSMyKO1Zp3bQWaXxMbZu7zCjMnOj7VUYtTdLqMbZ89JgTWPPUoYPkydHSkSoBCP67/CsNczeHWW1Rg6Vr5hYqp3NSsEJdLhf2s3OPe4jU/0OpnH+YzPwZILe+uPwsSzsFRWae3kTbVhtWXuZc/Lfx3KOxeR2FZWs4oJIjN7EiJzGuvvDwndk4WgRD++XtEMfSkVl2PB2CU8hcG2yKcaVQDSLBwMKHqwsgy+K/wPmclLtkKZvgtsu23iL2iNfTyOvV3ewGrBZ841hlUjyO5I+oOXz0KzPkKdFyGYRSQk6WlJdoQ8tLYmLUCkIiChUz2w+7iAL9qMK3iTmUUwIDAQAB-----END PUBLIC KEY-----
-----BEGIN RSA PRIVATE KEY-----MIIEowIBAAKCAQEA3+v1KRkLSMyKO1Zp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