Python에서 보안 암호화를 보장하는 방법은 무엇입니까?

DDD
풀어 주다: 2024-10-22 21:29:30
원래의
896명이 탐색했습니다.

How to Ensure Secure Encryption in Python?

대칭 키를 사용한 보안 암호화

Python에서 보안 암호화를 위해 권장되는 접근 방식은 암호화 라이브러리의 Fernet 레시피를 사용하는 것입니다. 무결성 확인을 위해 HMAC와 AES CBC 암호화를 사용하여 변조 및 무단 복호화로부터 데이터를 효과적으로 보호합니다.

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으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!