首頁  >  文章  >  後端開發  >  如何在 Python 中安全地加密受密碼保護的字串?

如何在 Python 中安全地加密受密碼保護的字串?

Susan Sarandon
Susan Sarandon原創
2024-10-22 22:27:02150瀏覽

How Can I Securely Encrypt Password-Protected Strings in 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 模式分組密碼提供加密和完整性。

以上是如何在 Python 中安全地加密受密碼保護的字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn