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

Susan Sarandon
发布: 2024-10-22 22:27:02
原创
149 人浏览过

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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!