我加密字符串:
def encrypt(self, message):
obj = AES.new('This is a key123'.encode("utf8"), AES.MODE_CFB, 'This is an IV456'.encode("utf8"))
encrypted = obj.encrypt(message.encode("utf8"))
return encrypted如何将加密后的内容存储在文件中,并使用以下命令读取以解密:
def decrypt(self, encrypted):
obj = AES.new('This is a key123'.encode("utf8"), AES.MODE_CFB, 'This is an IV456'.encode("utf8"))
decrypted=obj.decrypt(encrypted)
return decrypted发布于 2021-08-06 06:35:44
THe库"pycryptodome“有一个完整的运行示例,可以对文件进行AES加密,反之亦然。
我知道这个示例运行另一种模式并存储额外的数据,但这可能会对您有所帮助,因为使用静态IV是不安全的:https://pycryptodome.readthedocs.io/en/latest/src/examples.html
下面的代码生成一个新的AES128密钥,并将一段数据加密到一个文件中。我们使用EAX模式,因为它允许接收器检测任何未经授权的修改(类似地,我们可以使用其他经过身份验证的加密模式,如GCM、CCM或SIV)。
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
key = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)
file_out = open("encrypted.bin", "wb")
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]
file_out.close()在另一端,接收方可以安全地将数据段加载回来(如果它们知道密钥的话!)。请注意,当检测到篡改时,代码会生成ValueError异常。
from Crypto.Cipher import AES
file_in = open("encrypted.bin", "rb")
nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ]
# let's assume that the key is somehow available again
cipher = AES.new(key, AES.MODE_EAX, nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)https://stackoverflow.com/questions/68677021
复制相似问题