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

DDD
發布: 2024-10-22 21:47:30
原創
485 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!