Python crypto rsa decrypt

Examples¶

The following code generates a new AES128 key and encrypts a piece of data into a file. We use the EAX mode because it allows the receiver to detect any unauthorized modification (similarly, we could have used other authenticated encryption modes like GCM, CCM or SIV).

from Crypto.Cipher import AES from Crypto.Random import get_random_bytes data = b'secret data' key = get_random_bytes(16) cipher = AES.new(key, AES.MODE_EAX) ciphertext, tag = cipher.encrypt_and_digest(data) file_out = open("encrypted.bin", "wb") [ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ] file_out.close() 

At the other end, the receiver can securely load the piece of data back (if they know the key!). Note that the code generates a ValueError exception when tampering is detected.

from Crypto.Cipher import AES file_in = open("encrypted.bin", "rb") nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ] file_in.close() # let's assume that the key is somehow available again cipher = AES.new(key, AES.MODE_EAX, nonce) data = cipher.decrypt_and_verify(ciphertext, tag) 

Generate an RSA key¶

The following code generates a new RSA key pair (secret) and saves it into a file, protected by a password. We use the scrypt key derivation function to thwart dictionary attacks. At the end, the code prints our the RSA public key in ASCII/PEM format:

from Crypto.PublicKey import RSA secret_code = "Unguessable" key = RSA.generate(2048) encrypted_key = key.export_key(passphrase=secret_code, pkcs=8, protection="scryptAndAES128-CBC") file_out = open("rsa_key.bin", "wb") file_out.write(encrypted_key) file_out.close() print(key.publickey().export_key()) 

The following code reads the private RSA key back in, and then prints again the public key:

from Crypto.PublicKey import RSA secret_code = "Unguessable" encoded_key = open("rsa_key.bin", "rb").read() key = RSA.import_key(encoded_key, passphrase=secret_code) print(key.publickey().export_key()) 

Generate public key and private key¶

The following code generates public key stored in receiver.pem and private key stored in private.pem . These files will be used in the examples below. Every time, it generates different public key and private key pair.

from Crypto.PublicKey import RSA key = RSA.generate(2048) private_key = key.export_key() file_out = open("private.pem", "wb") file_out.write(private_key) file_out.close() public_key = key.publickey().export_key() file_out = open("receiver.pem", "wb") file_out.write(public_key) file_out.close() 

Encrypt data with RSA¶

The following code encrypts a piece of data for a receiver we have the RSA public key of. The RSA public key is stored in a file called receiver.pem .

Читайте также:  Вся суть java разработчика

Since we want to be able to encrypt an arbitrary amount of data, we use a hybrid encryption scheme. We use RSA with PKCS#1 OAEP for asymmetric encryption of an AES session key. The session key can then be used to encrypt all the actual data.

As in the first example, we use the EAX mode to allow detection of unauthorized modifications.

from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from Crypto.Cipher import AES, PKCS1_OAEP data = "I met aliens in UFO. Here is the map.".encode("utf-8") file_out = open("encrypted_data.bin", "wb") recipient_key = RSA.import_key(open("receiver.pem").read()) session_key = get_random_bytes(16) # Encrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(recipient_key) enc_session_key = cipher_rsa.encrypt(session_key) # Encrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX) ciphertext, tag = cipher_aes.encrypt_and_digest(data) [ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ] file_out.close() 

The receiver has the private RSA key. They will use it to decrypt the session key first, and with that the rest of the file:

from Crypto.PublicKey import RSA from Crypto.Cipher import AES, PKCS1_OAEP file_in = open("encrypted_data.bin", "rb") private_key = RSA.import_key(open("private.pem").read()) enc_session_key, nonce, tag, ciphertext = \ [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ] file_in.close() # Decrypt the session key with the private RSA key cipher_rsa = PKCS1_OAEP.new(private_key) session_key = cipher_rsa.decrypt(enc_session_key) # Decrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce) data = cipher_aes.decrypt_and_verify(ciphertext, tag) print(data.decode("utf-8")) 

Источник

Читайте также:  Java http header set cookie

5. Usage¶

This section describes the usage of the Python-RSA module.

Before you can use RSA you need keys. You will receive a private key and a public key.

The private key is called private for a reason. Never share this key with anyone.

The public key is used for encrypting a message such that it can only be read by the owner of the private key. As such it’s also referred to as the encryption key. Decrypting a message can only be done using the private key, hence it’s also called the decryption key.

The private key is used for signing a message. With this signature and the public key, the receiver can verify that a message was signed by the owner of the private key, and that the message was not modified after signing.

5.1. Generating keys¶

You can use the rsa.newkeys() function to create a key pair:

>>> import rsa >>> (pubkey, privkey) = rsa.newkeys(512) 

Alternatively you can use rsa.PrivateKey.load_pkcs1() and rsa.PublicKey.load_pkcs1() to load keys from a file:

>>> import rsa >>> with open('private.pem', mode='rb') as privatefile: . keydata = privatefile.read() >>> privkey = rsa.PrivateKey.load_pkcs1(keydata) 

5.1.1. Time to generate a key¶

Generating a key pair may take a long time, depending on the number of bits required. The number of bits determines the cryptographic strength of the key, as well as the size of the message you can encrypt. If you don’t mind having a slightly smaller key than you requested, you can pass accurate=False to speed up the key generation process.

Another way to speed up the key generation process is to use multiple processes in parallel to speed up the key generation. Use no more than the number of processes that your machine can run in parallel; a dual-core machine should use poolsize=2 ; a quad-core hyperthreading machine can run two threads on each core, and thus can use poolsize=8 .

>>> (pubkey, privkey) = rsa.newkeys(512, poolsize=8) 

These are some average timings from my desktop machine (Linux 2.6, 2.93 GHz quad-core Intel Core i7, 16 GB RAM) using 64-bit CPython 2.7. Since key generation is a random process, times may differ even on similar hardware. On all tests, we used the default accurate=True .

Читайте также:  Php web application servers

Источник

Оцените статью