首页 > 后端开发 > Python教程 > 如何确保Python中的安全加密?

如何确保Python中的安全加密?

DDD
发布: 2024-10-22 21:29:30
原创
997 人浏览过

How to Ensure Secure Encryption in Python?

使用对称密钥进行安全加密

Python 中安全加密的推荐方法是使用加密库中的 Fernet 配方。它采用 AES CBC 加密和 HMAC 进行完整性验证,有效保护数据免遭篡改和未经授权的解密。

Fernet 加解密

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

# Generate a secret key for encryption
key = Fernet.generate_key()

# Encode a message (plaintext)
encoded_message = Fernet(key).encrypt(b"John Doe")

# Decode the encrypted message (ciphertext)
decoded_message = Fernet(key).decrypt(encoded_message)

print(decoded_message.decode())  # Output: John Doe</code>
登录后复制

密码衍生的 Fernet 密钥

虽然建议使用随机生成的密钥以确保安全,但如有必要,您也可以从密码派生密钥:

<code class="python">from cryptography.fernet import Fernet
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes

def derive_key(password):
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=secrets.token_bytes(16),
        iterations=100_000,
        backend=default_backend()
    )
    return b64e(kdf.derive(password.encode()))

# Generate a password using a key derivation function
key = derive_key(password)

# Encrypt and decrypt using the password-derived Fernet key
encoded_message = Fernet(key).encrypt(b"John Doe")
decoded_message = Fernet(key).decrypt(encoded_message)

print(decoded_message.decode())  # Output: John Doe</code>
登录后复制

隐藏数据

对于非敏感数据,请考虑使用 base64编码而不是加密:

<code class="python">from base64 import urlsafe_b64encode as b64e

# Encode data
encoded_data = b64e(b"Hello world!")

# Decode data
decoded_data = b64d(encoded_data)

print(decoded_data)  # Output: b'Hello world!'</code>
登录后复制

对数据进行签名

使用 HMAC 对数据进行签名以确保完整性:

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

# Sign data using a secret key
key = secrets.token_bytes(32)
signature = hmac.new(key, b"Data to sign", hashlib.sha256).digest()

# Verify the signature
def verify(data, signature, key):
    expected = hmac.new(key, data, hashlib.sha256).digest()
    return hmac.compare_digest(expected, signature)

# Verify the signature using the same key
print(verify(b"Data to sign", signature, key))  # Output: True</code>
登录后复制

其他:不安全方案的正确实现

AES CFB:

<code class="python">import secrets
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

backend = default_backend()

def aes_cfb_encrypt(message, key):
    algorithm = algorithms.AES(key)
    iv = secrets.token_bytes(algorithm.block_size // 8)
    cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
    encryptor = cipher.encryptor()
    return b64e(iv + encryptor.update(message) + encryptor.finalize())

def aes_cfb_decrypt(ciphertext, key):
    iv_ciphertext = b64d(ciphertext)
    algorithm = algorithms.AES(key)
    size = algorithm.block_size // 8
    iv, encrypted = iv_ciphertext[:size], iv_ciphertext[size:]
    cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
    decryptor = cipher.decryptor()
    return decryptor.update(encrypted) + decryptor.finalize()</code>
登录后复制

AES ECB:

<code class="python">from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend

backend = default_backend()

def aes_ecb_encrypt(message, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    encryptor = cipher.encryptor()
    padder = padding.PKCS7(cipher.algorithm.block_size).padder()
    padded_message = padder.update(message.encode()) + padder.finalize()
    return b64e(encryptor.update(padded_message) + encryptor.finalize())

def aes_ecb_decrypt(ciphertext, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    decryptor = cipher.decryptor()
    unpadder = padding.PKCS7(cipher.algorithm.block_size).unpadder()
    padded_message = decryptor.update(b64d(ciphertext)) + decryptor.finalize()
    return unpadder.update(padded_message) + unpadder.finalize()</code>
登录后复制

注意: AES ECB 不是推荐用于安全加密。

以上是如何确保Python中的安全加密?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板