首页  >  文章  >  后端开发  >  如何在 Python 中安全地加密受密码保护的字符串?

如何在 Python 中安全地加密受密码保护的字符串?

Susan Sarandon
Susan Sarandon原创
2024-10-22 22:27:02150浏览

How Can I Securely Encrypt Password-Protected Strings in Python?

受密码保护的字符串的安全加密

问题:

Python 缺乏内置的使用密码加密和解密字符串的机制。对于需要数据混淆而又没有强大安全措施的场景来说,这可能会出现问题。

解决方案:

密码学库,例如密码学,提供安全的加密方案。

使用 Fernet 进行对称密钥加密

Fernet 是使用密码学的最佳实践配方。它将 AES CBC 加密与 HMAC 签名、时间戳和版本信息相结合来保护数据。

<code class="python">from cryptography.fernet import Fernet

# Generate a random 32-byte key (securely store it)
key = Fernet.generate_key()

# Encrypt and decrypt messages using the key
def encrypt(message, key):
    return Fernet(key).encrypt(message.encode())

def decrypt(token, key):
    return Fernet(key).decrypt(token).decode()</code>

替代方法:

数据模糊:

如果不关心数据完整性,可以使用 Base64 编码进行模糊处理。

<code class="python">import base64

def obscure(data):
    return base64.urlsafe_b64encode(data)

def unobscure(obscured):
    return base64.urlsafe_b64decode(obscured)</code>

数据完整性:

HMAC 签名可以通过使用密钥和哈希算法计算签名来确保数据完整性。

<code class="python">import hmac
import hashlib

def sign(data, key, algorithm=hashlib.sha256):
    return hmac.new(key, data, algorithm).digest()

def verify(signature, data, key, algorithm=hashlib.sha256):
    return hmac.compare_digest(expected, signature)</code>

使用 AES-GCM 进行完整性加密

与 Fernet 类似,AES- GCM 使用 Galois / Counter 模式分组密码提供加密和完整性。

<code class="python">from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

def aes_gcm_encrypt(message, key):
    # ... (Implementation omitted for brevity)

def aes_gcm_decrypt(token, key):
    # ... (Implementation omitted for brevity)</code>

以上是如何在 Python 中安全地加密受密码保护的字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn