Home >Backend Development >Python Tutorial >How to encrypt and decrypt data in Python

How to encrypt and decrypt data in Python

WBOY
WBOYOriginal
2023-10-18 10:15:141000browse

How to encrypt and decrypt data in Python

How to encrypt and decrypt data in Python requires specific code examples

Data encryption and decryption are very important concepts in the field of information security. In practical applications, we often need to encrypt sensitive data to prevent unauthorized access and information leakage. Python is a powerful programming language that provides a wealth of libraries and functions to implement data encryption and decryption operations. This article will introduce some commonly used encryption algorithms and specific code examples for implementing data encryption and decryption in Python.

1. MD5 encryption algorithm

MD5 (Message-Digest Algorithm 5) is a commonly used hash function used to encrypt data of any length. It converts messages of any length into a 128-bit digital fingerprint to ensure data integrity and non-tamperability.

In Python, we can use the hashlib library to implement the MD5 encryption algorithm. The following is a sample code:

import hashlib

def md5_encrypt(data):
    md5 = hashlib.md5()
    md5.update(data.encode(encoding='utf-8'))
    encrypt_data = md5.hexdigest()
    return encrypt_data

# 测试示例
data = 'hello world'
encrypted_data = md5_encrypt(data)
print("加密后的数据:", encrypted_data)

Running results:

加密后的数据: 5eb63bbbe01eeed093cb22bb8f5acdc3

2. AES encryption algorithm

AES (Advanced Encryption Standard) is an advanced encryption standard that is widely used in Various encryption scenarios. It uses symmetric key encryption to perform fast and secure encryption and decryption operations on data.

In Python, we can use the pycryptodome library to implement the AES encryption algorithm. The following is a sample code:

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

def aes_encrypt(data, key):
    cipher = AES.new(key, AES.MODE_EAX)
    nonce = cipher.nonce
    ciphertext, tag = cipher.encrypt_and_digest(data.encode())
    encrypted_data = nonce + ciphertext + tag
    return encrypted_data

def aes_decrypt(encrypted_data, key):
    nonce = encrypted_data[:16]
    ciphertext = encrypted_data[16:-16]
    tag = encrypted_data[-16:]
    cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
    data = cipher.decrypt_and_verify(ciphertext, tag)
    return data.decode()

# 测试示例
data = 'hello world'
key = get_random_bytes(16)
encrypted_data = aes_encrypt(data, key)
print("加密后的数据:", encrypted_data)
decrypted_data = aes_decrypt(encrypted_data, key)
print("解密后的数据:", decrypted_data)

Running results:




解密后的数据: hello world

3. RSA encryption algorithm

RSA (Rivest-Shamir-Adleman) is an asymmetric encryption algorithm. Commonly used for data encryption and digital signatures. It uses two keys, the public key is used to encrypt data and the private key is used to decrypt data.

In Python, we can use the cryptography library to implement the RSA encryption algorithm. The following is a sample code:

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.backends import default_backend

def rsa_encrypt(data, public_key):
    public_key = serialization.load_pem_public_key(public_key, backend=default_backend())
    encrypted_data = public_key.encrypt(data.encode(), padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
    return encrypted_data

def rsa_decrypt(encrypted_data, private_key):
    private_key = serialization.load_pem_private_key(private_key, password=None, backend=default_backend())
    decrypted_data = private_key.decrypt(encrypted_data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
    return decrypted_data.decode()

# 测试示例
data = 'hello world'
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
private_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption())
public_key = private_key.public_key()
public_pem = public_key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo)
encrypted_data = rsa_encrypt(data, public_pem)
print("加密后的数据:", encrypted_data)
decrypted_data = rsa_decrypt(encrypted_data, private_pem)
print("解密后的数据:", decrypted_data)

Running results:

解密后的数据: hello world

Through the above sample code, we can see how to use different encryption algorithms to encrypt and decrypt data in Python. Choosing an appropriate encryption algorithm and key length, and following secure coding practices, will ensure data confidentiality and integrity. Please note that the sample code in this article is for reference only. In actual application, details such as key management and data transmission security need to be considered.

The above is the detailed content of How to encrypt and decrypt data in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn