ホームページ  >  記事  >  バックエンド開発  >  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>

使用例:

<code class="python">data = b"Hello world!"
key = secrets.token_bytes(32)
signature = sign(data, key)

if verify(signature, data, key):
    print("Signature is valid")
else:
    print("Signature is invalid")</code>

以上がPython でパスワードを使用して文字列を安全に暗号化し、難読化する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。