介绍
在网络通信和数据存储中,保护敏感信息的安全性至关重要。Python中的cryptography库提供了一种强大而简单的方法,通过其Fernet加密算法,可以轻松加密和解密文本信息。本文将介绍如何使用cryptography库的Fernet模块创建一个简单的文本加密工具。
安装cryptography库
首先,确保你的Python环境中已经安装了cryptography库。如果未安装,可以使用以下命令进行安装:
1
| pip install cryptography
|
如果遇到问题可以参考以下的文章:
安装cryptography报错:Failed building wheel for cryptography-CSDN博客
pip安装cryptography时出错,怎么解决? - 知乎 (zhihu.com)
Python 安装Python Cryptography包失败解决方案|极客教程 (geek-docs.com)
编写代码
创建一个Python脚本,我们将在其中使用cryptography库的Fernet来进行文本加密和解密。下面是一个简单的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend from cryptography.fernet import Fernet
def generate_key(): return Fernet.generate_key()
def encrypt_text(key, plaintext): cipher = Fernet(key) encrypted_text = cipher.encrypt(plaintext.encode()) return encrypted_text
def decrypt_text(key, ciphertext): cipher = Fernet(key) decrypted_text = cipher.decrypt(ciphertext).decode() return decrypted_text
def main(): key = generate_key()
plaintext = "Hello, cryptography!"
ciphertext = encrypt_text(key, plaintext) print(f"Encrypted Text: {ciphertext}")
decrypted_text = decrypt_text(key, ciphertext) print(f"Decrypted Text: {decrypted_text}")
if __name__ == "__main__": main()
|
示例
下载
Github