python 数据加密
时间: 2023-11-08 09:02:38 浏览: 40
在Python中,可以使用各种库和算法来进行数据加密。以下是一些常见的方法:
1. 使用hashlib库进行哈希加密:hashlib库提供了多个哈希算法(如MD5、SHA-1、SHA-256等),可以将数据转换为固定长度的哈希值。这种加密是单向的,无法恢复原始数据。
示例代码:
```python
import hashlib
data = "Hello, World!"
hashed_data = hashlib.sha256(data.encode()).hexdigest()
print(hashed_data)
```
2. 使用cryptography库进行对称加密:cryptography库提供了各种对称加密算法(如AES、DES等),可以使用相同的密钥进行加密和解密。
示例代码:
```python
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
data = "Hello, World!"
encrypted_data = cipher_suite.encrypt(data.encode())
decrypted_data = cipher_suite.decrypt(encrypted_data).decode()
print(decrypted_data)
```
3. 使用rsa库进行非对称加密:rsa库提供了RSA算法,它使用公钥进行加密,私钥进行解密。
示例代码:
```python
from rsa.key import newkeys, PublicKey
public_key, private_key = newkeys(1024)
data = "Hello, World!"
encrypted_data = public_key.encrypt(data.encode(), 32)
decrypted_data = private_key.decrypt(encrypted_data).decode()
print(decrypted_data)
```