我有一个存储用户凭据的文件。我计划对其进行一次加密,然后在需要从文件中获取凭据时再执行解密和加密过程.Below是我原始文件的内容
{"customer1": {"tool_id": "earth", "user": "myuser", "pwd": "mypwd", "acc_id": "myaccount", "app_id": "myapp"}}
{"customer2": {"tool_id": "venus", "app_id": "myapp2", "api_key": "mykey"}}
我有以下程序来进行加密和解密
import os
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
def encrypt(key, filename):
chunksize = 64 * 1024
outputFile = "credentials.txt"
filesize = str(os.path.getsize(filename)).zfill(16)
IV = Random.new().read(16)
encryptor = AES.new(getKey(key), AES.MODE_CBC, IV)
with open(filename, 'rb') as infile:
with open(outputFile, 'wb') as outfile:
outfile.write(filesize.encode('utf-8'))
outfile.write(IV)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += b' ' * (16 - (len(chunk) % 16))
outfile.write(encryptor.encrypt(chunk))
def decrypt(key, filename):
chunksize = 64 * 1024
outputFile = filename
with open(filename, 'rb') as infile:
filesize = int(infile.read(16))
IV = infile.read(16)
decryptor = AES.new(getKey(key), AES.MODE_CBC, IV)
with open(outputFile, 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(filesize)
def getKey(password):
hasher = SHA256.new(password.encode('utf-8'))
return hasher.digest()
我计划对我的文件使用相同的命名约定来进行加密和解密。
第一次进行加密时
encrypt("poplo1234", "credentials.txt")
能够进行加密(对于相同的文件名)
当我尝试解密时
decrypt("poplo1234", "credentials.txt")
无法执行此操作。但是,在加密时,如果我为生成的新文件指定了不同的文件名并对其进行解密,则可以正常工作。
为什么我遇到这样的行为?我怎样才能确保多次使用相同的文件名进行加密和解密。
答案 0 :(得分:0)
问题是尝试同时读取和写入同一文件。解决方案是写入临时文件,关闭文件后重命名临时文件。
答案 1 :(得分:0)
这是一个对我有用的例子!该脚本采用一个zip文件等。hello.zip使用名称hello.zip.enc对其进行加密,然后使用名称hello_end.zip对其进行解密。
from Crypto.Cipher import AES
key = '0123456789abcdef'
IV = 16 * '\x00' # Initialization vector: discussed later
mode = AES.MODE_CFB
encryptor = AES.new(key, mode, IV=IV)
file = open("hello.zip", "rb")
text = file.read()
file.close()
ciphertext = encryptor.encrypt(text)
encr_file = open("hello.zip.enc", "wb")
encr_file.write(ciphertext)
encr_file.close()
final_file = open("hello.zip.enc", "rb")
xen_text = final_file.read()
plaintext = encryptor.decrypt(xen_text)
final_file.close()
end = open("hello_end.zip", "wb")
end.write(plaintext)
end.close()
使用CFB模式以免弄乱填充