首頁  >  文章  >  後端開發  >  如何在 Python 中使用密碼安全地加密和模糊字串?

如何在 Python 中使用密碼安全地加密和模糊字串?

DDD
DDD原創
2024-10-22 21:47:30486瀏覽

How to Safely Encrypt and Obscure Strings Using Passwords in Python?

在Python 中使用密碼加密字串

免責聲明:

加密是資料安全的關鍵方面,它應極其小心地處理。錯誤地實施加密可能會使您的資料容易受到攻擊。考慮使用完善的程式庫並遵循安全加密的最佳實踐。

使用加密庫:Fernet

Python 的加密庫提供了一種用戶友好且安全的解決方案,用於使用密碼加密字串。 Fernet 是密碼學中的內建配方,可簡化加密流程。

產生金鑰:

要使用 Fernet,您首先需要產生一個金鑰。將此密鑰保密至關重要。

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

key = Fernet.generate_key()  # Store this securely</code>

加密:

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

def encrypt(message: bytes, key: bytes) -> bytes:
    return Fernet(key).encrypt(message)</code>

解密:

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

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

密碼🎜>

模糊資料
<code class="python">message = "John Doe"
encrypted_token = encrypt(message.encode(), key)
decrypted_message = decrypt(encrypted_token, key).decode()

print(decrypted_message)  # Output: John Doe</code>

如果您需要模糊資料而不是加密數據,可以使用base64 編碼:

<code class="python">import base64

def obscure(data: bytes) -> bytes:
    return base64.b64encode(data)

def unobscure(obscured: bytes) -> bytes:
    return base64.b64decode(obscured)</code>
用法範例:

用法範例:

<code class="python">data = b"Hello world!"
obscured = obscure(data)
unobscured = unobscure(obscured)

print(unobscured.decode())  # Output: Hello world!</code>
驗證資料完整性

如果需要在不加密的情況下確保資料完整性,可以使用HMAC 簽章:

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

def sign(data: bytes, key: bytes) -> bytes:
    return hmac.new(key, data, hashlib.sha256).digest()

def verify(signature: bytes, data: bytes, key: bytes) -> bool:
    return hmac.compare_digest(hmac.new(key, data, hashlib.sha256).digest(), signature)</code>

用法範例:

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

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