4

I am writing a script to encrypt files in Python using RSA. I have successfully encrypted the original file and saved it to another file. When decrypting the encrypted file, the code is running, but when I am opening the image it is showing that the file is not a .jpg type file. The values n, d and e are stored in nfile, dfile, and efile, respectively.

Here's the encryption and decryption part of the code:

 if myMode == 'encrypt':

    n = open('nfile.pem', 'r')
    e = open('efile.pem', 'r')
    n1 = int(n.read()) 
    e1 = int(e.read())
    translated = str(pow(content1, e1, n1))      
    print(translated)

elif myMode == 'decrypt':

    fileobj2 = open('encrypted.jpg', 'rb')
    content2 = fileobj2.read
    content3 = int.from_bytes(b'content2', byteorder='big')
    fileobj2.close()
    n = open('nfile.pem', 'r')
    d = open('dfile.pem', 'r')
    n1 = int(n.read()) 
    d1 = int(d.read())
    translated = str(pow(content3, d1, n1))  
    translated1 = str.encode(translated)

# Write out the translated message to the output file.

outputFileObj = open('decrypted1.jpg', 'wb')

outputFileObj.write(translated1)

outputFileObj.close()

Here, encrypted.jpg is the file that is generated after encryption. The attached image is the error that I am facing

enter image description here

Looking forward to suggestions.

Andrew Palmer
  • 2,693
  • 2
  • 13
  • 14
Sandipan
  • 683
  • 8
  • 25

1 Answers1

3

Your N the modulus is too small to directly encrypt the message. For this to work N would need to be at least as long as the message in bits. Moduli with a million or so bits are quite impractical. I once tried 32786 bit RSA keys at the time it took a day to generate one key pair. This is why the message is encrypted with AES and the AES key is then encrypted with RSA. The AES key is a lot smaller than the message so keys with a few thousand bits suffice.

Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • but i think the error is in the way i am saving data into files in both encryption and decryption – Sandipan Dec 03 '18 at 09:12
  • 1
    Sure but it is also that your encrypt function projects into a subspace from which the message can not be uniquely recovered from even if the key is known. The same occurs with any trapdoor function like a hash function the output does not uniquely determine a single message but rather a set of messages that the injection maps to the same ciphertext. – Dan D. Dec 03 '18 at 09:58