python字符串加密的方法是什么

1224
2024/2/27 9:51:54
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Python中常见的字符串加密方法包括:

  1. 使用 hashlib 模块进行哈希加密,如 MD5、SHA-1、SHA-256 等加密算法。 示例代码:
import hashlib

text = "Hello, World!"
hashed_text = hashlib.md5(text.encode()).hexdigest()
print(hashed_text)
  1. 使用 base64 模块进行 base64 编码。 示例代码:
import base64

text = "Hello, World!"
encoded_text = base64.b64encode(text.encode()).decode()
print(encoded_text)
  1. 使用 cryptography 模块进行对称加密或非对称加密。 示例代码:
from cryptography.fernet import Fernet

key = Fernet.generate_key()
cipher = Fernet(key)

text = "Hello, World!"
encrypted_text = cipher.encrypt(text.encode())
print(encrypted_text)

decrypted_text = cipher.decrypt(encrypted_text).decode()
print(decrypted_text)

以上是几种常见的字符串加密方法,具体选择哪种方法取决于加密需求和安全性要求。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 如何在Python中管理项目依赖关系