python 加密解密
时间: 2024-01-16 07:18:54 浏览: 145
以下是Python中常用的加密解密方法:
1. 使用hashlib库进行哈希加密:
```python
import hashlib
# 创建md5对象
md5 = hashlib.md5()
# 更新要加密的数据
md5.update("Hello World".encode('utf-8'))
# 获取加密后的结果
result = md5.hexdigest()
print("MD5加密结果:", result)
```
2. 使用base64库进行Base64编码和解码:
```python
import base64
# 编码
encoded_str = base64.b64encode("Hello World".encode('utf-8'))
print("Base64编码结果:", encoded_str)
# 解码
decoded_str = base64.b64decode(encoded_str).decode('utf-8')
print("Base64解码结果:", decoded_str)
```
3. 使用cryptography库进行对称加密和解密:
```python
from cryptography.fernet import Fernet
# 生成密钥
key = Fernet.generate_key()
# 创建加密对象
cipher_suite = Fernet(key)
# 加密
cipher_text = cipher_suite.encrypt(b"Hello World")
print("对称加密结果:", cipher_text)
# 解密
plain_text = cipher_suite.decrypt(cipher_text)
print("对称解密结果:", plain_text.decode('utf-8'))
```
4. 使用cryptography库进行非对称加密和解密:
```python
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization
# 生成密钥对
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
# 加密
cipher_text = public_key.encrypt(
b"Hello World",
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print("非对称加密结果:", cipher_text)
# 解密
plain_text = private_key.decrypt(
cipher_text,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print("非对称解密结果:", plain_text.decode('utf-8'))
```
阅读全文