python - 使用python中保存的RSA密钥加密文件
问题描述
我正在尝试使用由另一个脚本生成并保存到 .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 和文件处理的新手,所以我认为问题在于我如何处理关键文件和输入文件。期待一些建议。
这是我的加密文件的代码:
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()
解决方案
您需要以二进制模式打开文件,而不是文本(默认)。
转动
fileObj = open(inputFilename)
进入
fileObj = open(inputFilename, "rb")
并将.read()
返回bytes
(即二进制数据),而不是str
(即文本)。
推荐阅读
- javascript - 使用 Object Javascript 在 foreach 循环中的最后一次迭代
- postman - 邮递员在收集开始时定义变量列表一次
- javascript - 如何从“日期范围选择器”禁用每天的“点击”事件?
- embedded - 使用 srec_cat 加入三个二进制文件并填充漏洞
- ember.js - Ember-cli-build,排除组件 ember 插件
- python - 如何从 Process- 或 Thread 实例返回值?
- javascript - Axios 在控制台上打印值但返回未定义
- linux - 在 @INC 中找不到 Parallel/ForkManager.pm
- c++ - C和C++中前缀自增运算符的区别
- php - Laravel Mail 未将变量传递给刀片模板