Skip to main content
 首页 » 编程设计

python之在 Python 中从文件中存储和读取加密字符串

2024年10月25日22Terrylee

我正在使用 AES(来自 PyCrypto)加密密码并将其存储在文件中。文件格式为:

user:username 
key:<encrypted key> 

这是我用于加密的方法:

BLOCK_SIZE = .. 
PADDING = .. 
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING 
 
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) 
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) 
cipher = AES.new("abcdefgh12345678") 
 
encrypted_key = EncodeAES(cipher, 'ABC123') 

现在,我如何从文件中读取 key 来解密它?如果我使用 line.split(":"),如果加密 key 本身具有“:”作为字符,是否会导致问题?

有没有办法在加密时避免“:”?还是有更好的方法来存储 key ?我不能使用散列,因为我需要一些其他功能的 key 。谢谢。

请您参考如下方法:

Now, how do I read the key from the file for decrypting it? If I use line.split(":"), wouldn't it cause problem if the encrypted key itself had ":" as a character?

当然会——这就是为什么 split有第二个可选参数 max_split:

key, value = line.split(':', 1) 

或者,您可以使用 partition :

key, _, value = line.partition(':') 

两者之间的区别在于根本没有冒号时会发生什么;前者将返回一个元素,给你一个 ValueError 试图将它解包成两个变量,而后者只会给你一个空的 value。


但是,值得注意的是,如果您使用的是 Base 64,: 永远不会出现在第一位。 Base 64 使用的唯一字符是 A-Z, a-z, 0-9、+ 和 /。有一些 Base 64 变体,也许其中一个确实使用了 :,但是标准版本,如 Python 的 base64 模块所应用的,没有。