使用python中保存的RSA密钥加密文件

时间:2018-12-02 17:01:20

标签: python python-3.x rsa file-handling public-key-encryption

我正在尝试使用由另一个脚本生成并保存到.pem文件中的RSA密钥对图像文件进行加密。当我尝试对文件进行加密时,显示此类错误

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

我是python和文件处理的新手,所以我认为问题出在我如何处理密钥文件和inputfile的方式上。期待一些建议。

这里是我的加密文件的代码:

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()

1 个答案:

答案 0 :(得分:1)

您需要以二进制模式而不是文本(默认)打开文件。

打开

fileObj = open(inputFilename)

进入

fileObj = open(inputFilename, "rb")

.read()将返回bytes(即二进制数据),而不是str(即文本)。