RSA encryption and decryption in Python - python

I need help using RSA encryption and decryption in Python.
I am creating a private/public key pair, encrypting a message with keys and writing message to a file. Then I am reading ciphertext from file and decrypting text using key.
I am having trouble with the decryption portion. As you can see in my code below, when I put in decrypted = key.decrypt(message) that the program works, yet the decrypted message is encrypted again. It seems like it is not reading the ciphertext from the file.
Can anyone help me write this code so decryption reads ciphertext from file and then uses key to decrypt ciphertext?
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys
publickey = key.publickey # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open ('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(message)
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()

In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key
publickey = key.publickey() # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print('encrypted message:', encrypted) #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
print('decrypted', decrypted)
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()

PKCS#1 OAEP is an asymmetric cipher based on RSA and the OAEP padding
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import PKCS1_OAEP
def rsa_encrypt_decrypt():
key = RSA.generate(2048)
private_key = key.export_key('PEM')
public_key = key.publickey().exportKey('PEM')
message = input('plain text for RSA encryption and decryption:')
message = str.encode(message)
rsa_public_key = RSA.importKey(public_key)
rsa_public_key = PKCS1_OAEP.new(rsa_public_key)
encrypted_text = rsa_public_key.encrypt(message)
#encrypted_text = b64encode(encrypted_text)
print('your encrypted_text is : {}'.format(encrypted_text))
rsa_private_key = RSA.importKey(private_key)
rsa_private_key = PKCS1_OAEP.new(rsa_private_key)
decrypted_text = rsa_private_key.decrypt(encrypted_text)
print('your decrypted_text is : {}'.format(decrypted_text))

# coding: utf-8
from __future__ import unicode_literals
import base64
import os
import six
from Crypto import Random
from Crypto.PublicKey import RSA
class PublicKeyFileExists(Exception): pass
class RSAEncryption(object):
PRIVATE_KEY_FILE_PATH = None
PUBLIC_KEY_FILE_PATH = None
def encrypt(self, message):
public_key = self._get_public_key()
public_key_object = RSA.importKey(public_key)
random_phrase = 'M'
encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
# use base64 for save encrypted_message in database without problems with encoding
return base64.b64encode(encrypted_message)
def decrypt(self, encoded_encrypted_message):
encrypted_message = base64.b64decode(encoded_encrypted_message)
private_key = self._get_private_key()
private_key_object = RSA.importKey(private_key)
decrypted_message = private_key_object.decrypt(encrypted_message)
return six.text_type(decrypted_message, encoding='utf8')
def generate_keys(self):
"""Be careful rewrite your keys"""
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
private, public = key.exportKey(), key.publickey().exportKey()
if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
raise PublicKeyFileExists('Файл с публичным ключом существует. Удалите ключ')
self.create_directories()
with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
private_file.write(private)
with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
public_file.write(public)
return private, public
def create_directories(self, for_private_key=True):
public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
if not os.path.exists(public_key_path):
os.makedirs(public_key_path)
if for_private_key:
private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
if not os.path.exists(private_key_path):
os.makedirs(private_key_path)
def _get_public_key(self):
"""run generate_keys() before get keys """
with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
return _file.read()
def _get_private_key(self):
"""run generate_keys() before get keys """
with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
return _file.read()
def _to_format_for_encrypt(self, value):
if isinstance(value, int):
return six.binary_type(value)
for str_type in six.string_types:
if isinstance(value, str_type):
return value.encode('utf8')
if isinstance(value, six.binary_type):
return value
And use
KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS
class TestingEncryption(RSAEncryption):
PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'
# django/flask
from django.core.files import File
class ProductionEncryption(RSAEncryption):
PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'
def _get_private_key(self):
"""run generate_keys() before get keys """
from corportal.utils import global_elements
private_key = global_elements.request.FILES.get('private_key')
if private_key:
private_key_file = File(private_key)
return private_key_file.read()
message = 'Hello мой friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)

Here is my implementation for python 3 and pycrypto
from Crypto.PublicKey import RSA
key = RSA.generate(4096)
f = open('/home/john/Desktop/my_rsa_public.pem', 'wb')
f.write(key.publickey().exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_private.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_public.pem', 'rb')
f1 = open('/home/john/Desktop/my_rsa_private.pem', 'rb')
key = RSA.importKey(f.read())
key1 = RSA.importKey(f1.read())
x = key.encrypt(b"dddddd",32)
print(x)
z = key1.decrypt(x)
print(z)

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
secret_message = b'ATTACK AT DAWN'
### First, make a key and save it
key = RSA.generate(2048)
with open( 'mykey.pem', 'wb' ) as f:
f.write( key.exportKey( 'PEM' ))
### Then use key to encrypt and save our message
public_crypter = PKCS1_OAEP.new( key )
enc_data = public_crypter.encrypt( secret_message )
with open( 'encrypted.txt', 'wb' ) as f:
f.write( enc_data )
### And later on load and decode
with open( 'mykey.pem', 'r' ) as f:
key = RSA.importKey( f.read() )
with open( 'encrypted.txt', 'rb' ) as f:
encrypted_data = f.read()
public_crypter = PKCS1_OAEP.new( key )
decrypted_data = public_crypter.decrypt( encrypted_data )

You can use simple way for genarate RSA . Use rsa library
pip install rsa

Watch out using Crypto!!!
It is a wonderful library but it has an issue in python3.8 'cause from the library time was removed the attribute clock(). To fix it just modify the source in /usr/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.pyline 77 changing t = time.clock() int t = time.perf_counter()

Related

Order of operations for cryto nodes/algorithms?

#I am trying to make a compiler with dummy data via a JSON. I have to encrypt it as a .bin and #then hash it and export it as a .blob file. Is there a certain order of operations when it comes #to all of theses cryptography nodes/algorithms? Anyways I am able to encrypt the json and then #turn it into a .bin. All I have to do now is hash it & export it as a .blob. Is there a certain #order I need to do this process? Thank you and have a good day.
#! /usr/bin/env python3
import os
import json
import hashlib #justin import
# import rsa
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.asymmetric import ec
from base64 import b64encode, b64decode
key = os.urandom(16)
iv = os.urandom(16)
output_list = []
def encrypt_input(elements, num, type):
for i in range(1, num + 1):
if str(i) in elements:
if type == 'uint32_t':
value = int(elements[str(i)])
plaintext = value.to_bytes(4, 'big', signed=False)
elif type == 'hex':
value = (elements[str(i)])
plaintext = bytes.fromhex(value)
else:
value = 0
if type == 'uint32_t':
plaintext = value.to_bytes(4, 'big', signed=False)
elif type == 'hex':
plaintext = value.to_bytes(32, 'big', signed=False)
cipher = Cipher(algorithms.AES(key), modes.CTR(iv))
encryptor = cipher.encryptor()
output_list.append(encryptor.update(plaintext) + encryptor.finalize())
with open(filename, mode='rb') as input_file:
file_contents = input_file.read()
cipher = Cipher(algorithms.AES(key), modes.CTR(iv))
encryptor = cipher.encryptor()
file_length = len(file_contents).to_bytes(4, 'big', signed=False)
output_list.append(encryptor.update(file_length) + encryptor.finalize)
encryptor = cipher.encryptor()
ciphertext - encryptor.update(file_contents) + encryptor.finalize()
output_list.append(ciphertext)
with open('input.json') as json_file:
data = json.load(json_file)
encrypt_input(data['parameter'], 4 , 'uint_32_t')
encrypt_input(data['user_data'], 128 , 'hex')
encrypt_input(data['internal_data'], 32 , 'hex')
encrypt_file_input(data['user_binary']['file'])
data = b''.join(output_list)
private_key = ec.generate_private_key(ec.SECP256R1())
signature = private_key.sign(data, ec.ECDSA(hashes.SHA256))
print(signature)
with open('sip.bin','w') as output:
output.write(signature+data)
# justin's code
# this example is taking our file and turning it into BLOB format
# after its encrypted, you are using hash function,
#using the cryptography library located here https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ec/#elliptic-curve-signature-algorithms
# https://github.com/pyca/cryptography/blob/main/src/cryptography/hazmat/primitives/hashes.py#L136-L139
# from cryptography.hazmat.primitives.asymmetric import utils
# chosen_hash = hashes.SHA256()
# hasher = hashes.Hash(chosen_hash)
# hasher.update(b"data & ")
# hasher.update(b"more data")
# digest = hasher.finalize()
# sig = private_key.sign(
# digest,
# ec.ECDSA(utils.Prehashed(chosen_hash))
# )
# #SHA256 Secure Hash Algorithm

How do i encrypt and decrypt files with PyCryptodome? (RSA)

I'm trying to encrypt and decrypt a file with PyCryptodome but without success. I can encrypt strings and data just fine but when trying to encrypt files it fails. I have 2 problems, first is that I can't encrypt larger strings. Witch i tried to solve by reading the file with a buffer. Second is that when I try to encrypt it as smaller buffers it just gives me an error "raise ValueError("Ciphertext with incorrect length.")"
My code looks like this:
from Crypto.Cipher import PKCS1_OAEP
import binascii
import ast
file_to_encrypt = "file_example_MP3_700KB.mp3"
buffer_size = 65536 # 64kb
input_file = open(file_to_encrypt, "rb")
output_file = open(file_to_encrypt + ".encrypted", "wb")
# Import keys
pub = open("publickey.txt", "rb")
pubKey = RSA.importKey(pub.read())
pub.close()
priv = open("privatekey.txt", "rb")
keyPair = RSA.importKey(priv.read())
priv.close()
# --------------------------------------------------------------
# Encrypt
encryptor = PKCS1_OAEP.new(pubKey)
buffer = input_file.read(buffer_size)
while len(buffer) > 0:
encrypted = encryptor.encrypt(buffer)
output_file.write(encrypted)
buffer = input_file.read(buffer_size)
input_file.close()
output_file.close()
# --------------------------------------------------------------
input_file = open(file_to_encrypt + ".encrypted", "rb")
output_file = open(file_to_encrypt + ".decrypted", "wb")
# Decrypt
decryptor = PKCS1_OAEP.new(keyPair)
buffer = input_file.read(buffer_size)
while len(buffer) > 0:
decrypted = decryptor.decrypt(ast.literal_eval(str(buffer)))
output_file.write(decrypted)
buffer = input_file.read(buffer_size)
input_file.close()
output_file.close()
# --------------------------------------------------------------
And generating the keys looks like this:
from Crypto.Cipher import PKCS1_OAEP
import binascii
import ast
# key generation
keyPair = RSA.generate(3072*2)
pubKey = keyPair.publickey()
# --------------------------------------------------------------
# Export keys
pub = open("publickey.txt", "wb")
pub.write(pubKey.exportKey('PEM'))
pub.close()
priv = open("privatekey.txt", "wb")
priv.write(keyPair.exportKey('PEM'))
priv.close()
# --------------------------------------------------------------
# Import keys
pub = open("publickey.txt", "rb")
pubKey = RSA.importKey(pub.read())
pub.close()
priv = open("privatekey.txt", "rb")
keyPair = RSA.importKey(priv.read())
priv.close()
# --------------------------------------------------------------
# encryption
msg = '550011'
encryptor = PKCS1_OAEP.new(pubKey)
encrypted = encryptor.encrypt(msg.encode())
# --------------------------------------------------------------
# decryption
decryptor = PKCS1_OAEP.new(keyPair)
decrypted = str(decryptor.decrypt(ast.literal_eval(str(encrypted))))[2:-1]
# --------------------------------------------------------------
print("Encrypted:", binascii.hexlify(encrypted))
print("Decrypted:", decrypted)
if msg == decrypted:
print("PASSED!")
else:
print("FAILED!")
Changing buffer_size fixes the first problem (that the data I'm trying to encrypt is too large.)
But I still can't decrypt my file after encrypting it.
Generating and importing keys works just fine. And encrypting and decrypting with them works just fine as well. As long as I'm only encrypting small strings and not files.

Python3 - How do I read a string of byte values and re-encode it as bytes?

I'm working on a tool that uses hex API keys to log a user into a remote hosted tool. For security purposes, I'm using Fernet to encrypt the keys locally and store them in a text file so the user doesn't have to enter them every time. We need to decrypt the API keys so the user can log in. The issue is that I'm loading the keys in from a text file, and I'm getting the following error when passing the string data back to Fernet:
ValueError: Fernet key must be 32 url-safe base64-encoded bytes.
Any idea what I'm doing wrong? Here are my functions:
# This function generates the local key file
def key_gen(access_key, secret_key):
from os import getcwd
from cryptography.fernet import Fernet
file_data = []
key = Fernet.generate_key()
encrypted_ak = encrypt_data(access_key, key)
encrypted_sk = encrypt_data(secret_key, key)
current_dir = getcwd()
key_file = current_dir + "\\tenableauth.txt"
file_data.append(key)
file_data.append(encrypted_ak)
file_data.append(encrypted_sk)
with open(key_file, 'w') as authentication_file:
for line in file_data:
authentication_file.writelines(str(line) + "\n")
return key_file
# This function reads the local key file, and is where I'm hitting problems. Lots of test code here.
def read_keys(file):
file_lines = []
with open(file, 'r') as authentication_file:
for line in authentication_file:
file_lines.append(line)
encryption_key = file_lines[0]
encryption_key = encryption_key.rstrip()
print(encryption_key)
print(repr(encryption_key))
decrypted_ak = decrypt_data(file_lines[1], encryption_key)
print(decrypted_ak)
def encrypt_data(data, key):
from cryptography.fernet import Fernet
data = data.encode()
encrypted_string = Fernet(key).encrypt(data)
return encrypted_string
def decrypt_data(data, key):
from cryptography.fernet import Fernet
decrypted_string = Fernet(key).decrypt(data)
return decrypted_string
An error like that means you are mixing and matching str and bytes object types, along the way incorrectly encoding / decoding between the types
I updated the code handling between str and bytes object types as below
# This function generates the local key file
def key_gen(access_key, secret_key):
from os import getcwd
from cryptography.fernet import Fernet
file_data = []
key = Fernet.generate_key()
encrypted_ak = encrypt_data(access_key, key)
encrypted_sk = encrypt_data(secret_key, key)
print(f"key {key}")
print(f"encrypted_sk {encrypted_sk}")
print(f"encrypted_ak {encrypted_ak}")
key_file = "tenableauth.txt"
file_data.append(key.decode('utf-8'))
file_data.append(encrypted_ak.decode('utf-8'))
file_data.append(encrypted_sk.decode('utf-8'))
with open(key_file, 'w') as authentication_file:
for line in file_data:
authentication_file.write(line + '\n')
return key_file
# This function reads the local key file, and is where I'm hitting problems. Lots of test code here.
def read_keys(file):
file_lines = []
with open(file, 'r') as authentication_file:
for line in authentication_file:
file_lines.append(line.encode('utf-8').rstrip())
key = file_lines[0]
encrypted_ak = file_lines[1]
encrypted_sk = file_lines[2]
print(f"key {key}")
print(f"encrypted_sk {encrypted_sk}")
print(f"encrypted_ak {encrypted_ak}")
decrypted_ak = decrypt_data(encrypted_ak, key)
print(decrypted_ak)
def encrypt_data(data, key):
from cryptography.fernet import Fernet
data = data.encode()
encrypted_string = Fernet(key).encrypt(data)
return encrypted_string
def decrypt_data(data, key):
from cryptography.fernet import Fernet
decrypted_string = Fernet(key).decrypt(data)
return decrypted_string
With the print statement I've added, invoking key_gen("yadayada", "hoho!!") prints
key b'BtP8iJwhWqfxX6i_HwSbRASh04w3V0Ypp-M2Ic23Xlc='
encrypted_sk b'gAAAAABf67lG1a_zotxaxeG3mR6sXIgQF6jtsS6Nt8FWP7EI2f73dtBLCwWBE9fTGvEHml_ivcKxSMUjMOgOWjGSOM0uTLSDCw=='
encrypted_ak b'gAAAAABf67lGphAR1gq65o_RB2cg-o5dCLICW7o8LceKAiTEP1N4nSqlqW9pSaLumxm6CeI4bwfirSZvPDPtUtlVMeCREttvTg=='
and in reverse invokeing read_keys('tenableauth.txt') prints
key b'BtP8iJwhWqfxX6i_HwSbRASh04w3V0Ypp-M2Ic23Xlc='
encrypted_sk b'gAAAAABf67lG1a_zotxaxeG3mR6sXIgQF6jtsS6Nt8FWP7EI2f73dtBLCwWBE9fTGvEHml_ivcKxSMUjMOgOWjGSOM0uTLSDCw=='
encrypted_ak b'gAAAAABf67lGphAR1gq65o_RB2cg-o5dCLICW7o8LceKAiTEP1N4nSqlqW9pSaLumxm6CeI4bwfirSZvPDPtUtlVMeCREttvTg=='
b'yadayada'
The very last line of output is b'yadayada' the key that was passed in.

Python3 - Encrypting and decrypting an image (Fernet) Issue

Good day,
I am doing an assignment for cryptography. It's an easy task I need to take any image, turn it into HEX, encrypt it and then decrypt it.
As I am working in Python and there was no specific encryption method in the task I just use Fernet.
I have an encryptor and decryptor scripts.
Encryption seems to be working because as a test I create a txt document with original HEX and after decryption the program states that original HEX and decrypted one are the same, however the decrypted image is not loading.
Could anyone help out a newbie?
Encryptor:
import binascii
from cryptography.fernet import Fernet
img = 'panda.png'
with open(img, 'rb') as f:
content = f.read()
hexValue = binascii.hexlify(content)
key = Fernet.generate_key()
with open('info/key.txt', mode='w+') as keyValue:
keyValue.write(key)
keyValue.seek(0)
f = Fernet(key)
encHexVal = f.encrypt(hexValue)
with open('info/encryptedHex.txt', mode='w+') as hexValueFile:
hexValueFile.write(encHexVal)
hexValueFile.seek(0)
a = f.decrypt(encHexVal)
with open('info/realValue.txt', mode='w+') as writeHex:
originalHex = writeHex.write(hexValue)
with open('info/realValue.txt', mode='r') as reading:
realValue = reading.read()
if realValue == a:
print("We're good to go!")
else:
print("Oops something went wrong. Check the source code.")
Decryptor:
import binascii
from cryptography.fernet import Fernet
with open('info/key.txt', mode='rb') as keyValue:
key = keyValue.read()
f = Fernet(key)
with open('info/encryptedHex.txt', mode='rb') as imageHexValue:
hexValue = imageHexValue.read()
a = f.decrypt(hexValue)
with open('info/realValue.txt', mode='r') as compare:
realContents = compare.read()
print("Small test in safe environment...")
if realContents == a:
print("All good!")
else:
print("Something is wrong...")
data = a.encode()
data = data.strip()
data = data.replace(' ', '')
data = data.replace('\n', '')
with open('newImage.png', 'wb') as file:
file.write(data)
I am using a random image from the internet of Po from Kung Fu Panda:
The principle problem is that although you hexlify then encrypt in the encryptor you don't unhexlify after decrypting in the decryptor. Its far more common to do things the other way, encrypt then hexlify so that the encrypted binary can be stored in regular text files or sent via http.
You have several problems with trying to write bytes objects to files open in text. I fixed those along the way. But it does leave me puzzled why a file called 'info/encryptedHex.txt' would be binary.
Encryptor
import binascii
from cryptography.fernet import Fernet
# Generate keyfile
#
# TODO: Overwrites key file on each run, invalidating previous
# saves. You could do `if not os.path.exists('info/key.txt'):`
key = Fernet.generate_key()
with open('info/key.txt', mode='wb') as keyValue:
keyValue.write(key)
# Encrypt image
img = 'panda.png'
with open(img, 'rb') as f:
content = f.read()
hexValue = binascii.hexlify(content)
f = Fernet(key)
encHexVal = f.encrypt(hexValue)
with open('info/encryptedHex.txt', mode='wb') as hexValueFile:
hexValueFile.write(encHexVal)
# Verification checks
a = f.decrypt(encHexVal)
# hexed bytes is same encoding as 'ascii'
with open('info/realValue.txt', mode='wb') as writeHex:
originalHex = writeHex.write(hexValue)
with open('info/realValue.txt', mode='r', encoding='ascii') as reading:
realValue = reading.read()
if realValue == a.decode('ascii'):
print("We're good to go!")
else:
print("Oops something went wrong. Check the source code.")
Decryptor
import binascii
from cryptography.fernet import Fernet
# Generate keyfile
#
# TODO: Overwrites key file on each run, invalidating previous
# saves. You could do `if not os.path.exists('info/key.txt'):`
key = Fernet.generate_key()
with open('info/key.txt', mode='wb') as keyValue:
keyValue.write(key)
# Encrypt image
img = 'panda.png'
with open(img, 'rb') as f:
content = f.read()
hexValue = binascii.hexlify(content)
f = Fernet(key)
encHexVal = f.encrypt(hexValue)
with open('info/encryptedHex.txt', mode='wb') as hexValueFile:
hexValueFile.write(encHexVal)
# Verification checks
a = f.decrypt(encHexVal)
# hexed bytes is same encoding as 'ascii'
with open('info/realValue.txt', mode='wb') as writeHex:
originalHex = writeHex.write(hexValue)
with open('info/realValue.txt', mode='r', encoding='ascii') as reading:
realValue = reading.read()
if realValue == a.decode('ascii'):
print("We're good to go!")
else:
print("Oops something went wrong. Check the source code.")
(base) td#timpad:~/dev/SO/Encrypting and decrypting in image$ cat de.py
import binascii
from cryptography.fernet import Fernet
with open('info/key.txt', mode='rb') as keyValue:
key = keyValue.read()
f = Fernet(key)
with open('info/encryptedHex.txt', mode='rb') as imageHexValue:
encHexValue = imageHexValue.read()
hexValue = f.decrypt(encHexValue)
binValue = binascii.unhexlify(hexValue)
with open('info/realValue.txt', mode='rb') as compare:
realContents = compare.read()
print("Small test in safe environment...")
if realContents == hexValue:
print("All good!")
else:
print("Something is wrong...")
with open('newImage.png', 'wb') as file:
file.write(binValue)

ValueError when reading RSA key from .PEM file using ImportKey

This documentation of PyCrypto for RSA
https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA-module.html mentions this how we are supposed to write and read keys to and from .PEM :
from Crypto.PublicKey import RSA
key = RSA.generate(2048)
f = open('mykey.pem','w')
f.write(RSA.exportKey('PEM'))
f.close()
...
f = open('mykey.pem','r')
key = RSA.importKey(f.read())
and this is how i have done it.
random_generator = Random.new().read
rsakey = RSA.generate(1024, random_generator)
f = open(email + '.pem', 'w')
cipher = PKCS1_OAEP.new(rsakey.publickey())
f.write(str(rsakey.exportKey("PEM")))
f.write(str(rsakey.publickey().exportKey("PEM")))
...
f = open(receiver + '.pem', 'r')
key = RSA.importKey(f.read())
pubkey = key.publickey()
f.close()
but it returns this error:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Crypto/PublicKey/RSA.py", line 682, in importKey
raise ValueError("RSA key format is not supported")
ValueError: RSA key format is not supported
writing the keys in "wb" mode solved the problem
random_generator = Random.new().read
rsakey = RSA.generate(1024, random_generator)
f = open(email + '.pem', 'wb')
cipher = PKCS1_OAEP.new(rsakey.publickey())
f.write(str(rsakey.exportKey("PEM")))
f.write(str(rsakey.publickey().exportKey("PEM")))
...
f = open(receiver + '.pem', 'r')
key = RSA.importKey(f.read())
pubkey = key.publickey()
f.close()

Categories

Resources