RSA encryption and decryption in Python RSA encryption and decryption in Python python python

RSA encryption and decryption in Python


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 Cryptofrom Crypto.PublicKey import RSAfrom Crypto import Randomimport astrandom_generator = Random.new().readkey = RSA.generate(1024, random_generator) #generate pub and priv keypublickey = key.publickey() # pub key export for exchangeencrypted = publickey.encrypt('encrypt this message', 32)#message to encrypt is in the above line 'encrypt this message'print('encrypted message:', encrypted) #ciphertextf = open ('encryption.txt', 'w')f.write(str(encrypted)) #write ciphertext to filef.close()#decrypted code belowf = 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 RSAfrom Crypto import Randomfrom Crypto.Cipher import PKCS1_OAEPdef 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-8from __future__ import unicode_literalsimport base64import osimport sixfrom Crypto import Randomfrom Crypto.PublicKey import RSAclass PublicKeyFileExists(Exception): passclass 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(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_KEYSclass TestingEncryption(RSAEncryption):    PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'    PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'# django/flaskfrom django.core.files import Fileclass 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)