Sandipan
Sandipan

Reputation: 703

Encrypting a file using saved RSA keys in python

I am trying to encrypt an image file using RSA keys that are generated by another script and saved into a .pem file. when i am trying to encrypt the file its showing errors like this

Traceback (most recent call last):
  File "rsaencrypt.py", line 85, in <module>
    main()
  File "rsaencrypt.py", line 45, in main
    content = fileObj.read()
  File "/usr/lib64/python3.7/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

I am new to python and file handling so i think the problem is in the way of how i am handling the files both the key files and the inputfile. Looking forward to some suggestion.

Heres the code of my encryption file:

import time, os, sys

def main():

inputFilename = 'img.jpg'

# BE CAREFUL! If a file with the outputFilename name already exists,

# this program will overwrite that file.

outputFilename = 'encrypted.jpg'

myKey = open("public_key.pem",'r')

myMode = 'encrypt' # set to 'encrypt' or 'decrypt'

# If the input file does not exist, then the program terminates early.

if not os.path.exists(inputFilename):

   print('The file %s does not exist. Quitting...' % (inputFilename))

   sys.exit()

# If the output file already exists, give the user a chance to quit.

if os.path.exists(outputFilename):

   print('This will overwrite the file %s. (C)ontinue or (Q)uit?' % (outputFilename))

   response = input('> ')

   if not response.lower().startswith('c'):

        sys.exit()

# Read in the message from the input file

fileObj = open(inputFilename)

content = fileObj.read()

fileObj.close()

print('%sing...' % (myMode.title()))

# Measure how long the encryption/decryption takes.

startTime = time.time()

if myMode == 'encrypt':

    translated = transpositionEncrypt.encryptMessage(myKey, content)

elif myMode == 'decrypt':

    translated = transpositionDecrypt.decryptMessage(myKey, content)

totalTime = round(time.time() - startTime, 2)

print('%sion time: %s seconds' % (myMode.title(), totalTime))

# Write out the translated message to the output file.

outputFileObj = open(outputFilename, 'w')

outputFileObj.write(translated)

outputFileObj.close()

print('Done %sing %s (%s characters).' % (myMode, inputFilename, len(content)))

print('%sed file is %s.' % (myMode.title(), outputFilename))

# If transpositionCipherFile.py is run (instead of imported as a module)

# call the main() function.

if __name__ == '__main__':

   main()

Upvotes: 0

Views: 1060

Answers (1)

AKX
AKX

Reputation: 168824

You need to open the file in binary mode, not text (which is the default).

Turn

fileObj = open(inputFilename)

into

fileObj = open(inputFilename, "rb")

and .read() will return bytes (i.e. binary data), not str (i.e. text).

Upvotes: 2

Related Questions