首页  >  文章  >  后端开发  >  如何在 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn