Home >Backend Development >Python Tutorial >What is the method of data encryption and decryption in python

What is the method of data encryption and decryption in python

WBOY
WBOYforward
2024-03-01 17:10:461422browse

What is the method of data encryption and decryption in python

In python, the commonly used data encryption and decryption methods are as follows:

  1. hashlib module: Use hash algorithm to encrypt data. Commonly used hash algorithms include MD5, SHA1, SHA256, etc. Data can be encrypted and decrypted using various hash algorithm functions in the hashlib library.

Sample code:

import hashlib

# 加密数据
data = "Hello World"
hashed_data = hashlib.sha256(data.encode()).hexdigest()
print(hashed_data)

# 解密数据
# 由于哈希算法是单向的,无法逆向解密,只能通过对比哈希值来验证数据的一致性
  1. base64 module: Base64 encode and decode data. Base64 encoding is an encoding method that converts binary data into printable ASCII characters. It is often used to transmit binary data in network transmission.

Sample code:

import base64

# 加密数据
data = "Hello World"
encoded_data = base64.b64encode(data.encode()).decode()
print(encoded_data)

# 解密数据
decoded_data = base64.b64decode(encoded_data).decode()
print(decoded_data)
  1. cryptography library: A powerful encryption and decryption library that provides a variety of encryption algorithms such as symmetric encryption, asymmetric encryption and hash algorithms.

Sample code:

from cryptography.fernet import Fernet

# 生成密钥
key = Fernet.generate_key()

# 加密数据
cipher_suite = Fernet(key)
data = "Hello World"
encrypted_data = cipher_suite.encrypt(data.encode()).decode()
print(encrypted_data)

# 解密数据
decrypted_data = cipher_suite.decrypt(encrypted_data.encode()).decode()
print(decrypted_data)

The above is the detailed content of What is the method of data encryption and decryption in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete