如何在python中加密和解密一个字符串? [英] How do I encrypt and decrypt a string in python?

查看:721
本文介绍了如何在python中加密和解密一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一个如何加密和解密一个字符串的时间。但是大部分是在2.7中,任何使用3.2的东西都不是让我打印出来或将它添加到一个字符串中。

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(一堆随机字母)

jgAKLJK34t3g (a bunch of random letters)



decoded = decode(encoded,"password")
print(decoded)




Hello stackoverflow!

Hello stackoverflow!

有没有这样做,使用python 3.X,当字符串被编码时,它仍然是一个字符串,而不是任何其他变量类型。

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.

推荐答案

查看 PyCrypto 。它支持Python 3.2,并且完全符合您的要求。

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

从他们的网站:

>>> 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'

如果要加密任何大小的消息使用 AES.MODE_CFB 而不是 AES.MODE_CBC

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

这篇关于如何在python中加密和解密一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆