问题描述
我正在使用 Python 2.7 。我有一个字母数字字符串,我要执行加密/解密。不管我做什么应该保持双向,结果应该是字母数字。
I am using Python 2.7. I have an alphanumeric string, on which I want to perform a encryption/decryption. Whatever I do should remain 2-way and the result should be alphanumeric too.
例如:
str = 'ma6546fbd'
encrypted_data = encrypt_function(str)
decrypted_data = decrypt_function(encrypted_data)
print decrypted_data # I get 'ma6546fbd'
我做了什么:
我写了一个函数
def xor_crypt_string(data, key):
return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
这需要数据和一个键并返回结果,问题是它包含特殊字符,我想避免的。
This takes the data and a key and returns the result, the problem is that it includes special characters too, which I want to avoid.
推荐答案
如果您想要严格的加密(读取不可破解),那么我将使用 from 这样的东西。
If you want serious encryption (read unbreakable) then I'd use AES from pycrypto something like this.
>>> from Crypto.Cipher import AES
>>> from Crypto import Random
>>> key = b'Sixteen byte key'
>>> iv = Random.new().read(AES.block_size)
>>> cipher = AES.new(key, AES.MODE_CFB, iv)
>>> msg = iv + cipher.encrypt(b'Attack at dawn')
>>> msg.encode("hex")
'e10e096aabff9db382abe8d704404995a7b64d72a4e1b9e5208912d206c4'
这是您的ascii消息。现在解码这样的消息
That is your ascii message. Now decode the message like this
>>> recv='e10e096aabff9db382abe8d704404995a7b64d72a4e1b9e5208912d206c4'
>>> cipher.decrypt(recv.decode("hex"))[len(iv):]
'Attack at dawn'
>>>
你自己组成的任何加密方法都会被专家和你所展示的加密方法容易地破解以上属于该类别。
Any encryption method you make up yourself will be easily breakable by an expert and the one you've shown above falls into that category.
这篇关于Python:双向字母数字加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!