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
Release: 2024-03-01 17:10:46
forward
1418 people have browsed it

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)

# 解密数据
# 由于哈希算法是单向的,无法逆向解密,只能通过对比哈希值来验证数据的一致性
Copy after login
  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)
Copy after login
  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)
Copy after login

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!

Related labels:
source:lsjlt.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template