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

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

问题描述

我一直在寻找如何加密和解密字符串的方法.但大部分是在 2.7 中,任何使用 3.2 的东西都不允许我打印它或将它添加到字符串中.

所以我想要做的是以下内容:

mystring = "你好,stackoverflow!"编码 = 编码(我的字符串,密码")打印(编码)

<块引用>

jgAKLJK34t3g(一堆随机字母)

decoded = decode(encoded,"password")打印(解码)

<块引用>

你好,stackoverflow!

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

解决方案

我在为 Windows 7 系统和 Python 3.5 编译所有最常提到的加密库时遇到了麻烦.

这是最终对我有用的解决方案.

from cryptography.fernet import Fernetkey = Fernet.generate_key() #这是你的密码"cipher_suite = Fernet(密钥)encoding_text = cipher_suite.encrypt(b"Hello stackoverflow!")解码文本 = cipher_suite.decrypt(encoded_text)

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.

解决方案

I had troubles compiling all the most commonly mentioned cryptography libraries on my Windows 7 system and for Python 3.5.

This is the solution that finally worked for me.

from cryptography.fernet import Fernet
key = Fernet.generate_key() #this is your "password"
cipher_suite = Fernet(key)
encoded_text = cipher_suite.encrypt(b"Hello stackoverflow!")
decoded_text = cipher_suite.decrypt(encoded_text)

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

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