如何将字符串加密到相同大小的字符串是Python

时间:2014-05-09 08:45:23

标签: python encryption pycrypto

我有大约500个字符串的字符串,我想加密它们,以便生成的字符串具有相同的长度(或略有不同)。我需要使用另一方知道的另一个“秘密”字符串进行双向加密和解密。它不需要非常安全,我更喜欢更快的解决方案。

2 个答案:

答案 0 :(得分:3)

来自此处的帖子:Encrypt string in Python

使用http://code.google.com/p/keyczar/

crypter = Crypter.Read("/path/to/your/keys")
ciphertext = crypter.Encrypt("Secret message")

答案 1 :(得分:2)

如果您想保留长度,则需要使用stream cipher

请注意,双方都需要知道密钥(秘密)和initialization vector(不是秘密,但必须是唯一的)。

在没有不同的IV的情况下重复使用相同的密钥是不安全的,因此您需要以某种方式通信新的IV,这有效地延长了您的加密包。

此外,您确实需要考虑重播攻击 - 如果有人拦截您的邮件然后一次又一次地发送邮件会发生什么。

这是RC4的简单示例,使用pycrypto,没有IV(RC4不支持它):

import Crypto.Cipher.ARC4
plaintext = "x" * 13
c1 = Crypto.Cipher.ARC4.new(key="1")
ciphertext = c.encrypt(plaintext)
assert len(ciphertext) == len(plaintext)
c2 = Crypto.Cipher.ARC4.new(key="1")
result = c2.descrypt(ciphertext)
assert result == plaintext