python数字加密输出,Python:双向字母数字加密

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.

For example:

str = 'ma6546fbd'

encrypted_data = encrypt_function(str)

decrypted_data = decrypt_function(encrypted_data)

print decrypted_data # I get 'ma6546fbd'

What have I done:

I have written a function

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.

解决方案

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'

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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值