如何给python 代码加密_如何在python中加密和解密一个字符串?

1586010002-jmsa.png

I have been looking for sometime on how to encrypt and decrypt a string. But most of it is in 2.7 and anything that is using 3.2 is not letting me print it or add it to a string.

So what I'm trying to do is the following:

mystring = "Hello stackoverflow!"

encoded = encode(mystring,"password")

print(encoded)

jgAKLJK34t3g (a bunch of random letters)

decoded = decode(encoded,"password")

print(decoded)

Hello stackoverflow!

Is there anyway of doing this, using python 3.X and when the string is encoded it's still a string, not any other variable type.

解决方案

Take a look at PyCrypto. It supports Python 3.2 and does exactly what you want.

From their pip website:

>>> from Crypto.Cipher import AES

>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')

>>> message = "The answer is no"

>>> ciphertext = obj.encrypt(message)

>>> ciphertext

'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'

>>> obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')

>>> obj2.decrypt(ciphertext)

'The answer is no'

If you want to encrypt a message of an arbitrary size use AES.MODE_CFB instead of AES.MODE_CBC.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值