转换加密方法Python
时间: 2023-11-05 21:10:20 浏览: 84
如果你想转换加密方法,可以使用Python中的不同加密库来实现。以下是一些常用的加密库及其示例用法:
1. hashlib库:提供许多安全哈希和消息摘要算法,例如MD5、SHA1、SHA256等。
示例代码:
```python
import hashlib
# 计算字符串的MD5哈希值
string = "Hello World"
hash_object = hashlib.md5(string.encode())
print(hash_object.hexdigest())
# 计算文件的SHA256哈希值
filename = "test.txt"
with open(filename, "rb") as f:
bytes = f.read()
hash_object = hashlib.sha256(bytes)
print(hash_object.hexdigest())
```
2. cryptography库:提供了更高级的加密算法实现,例如AES、RSA等。
示例代码:
```python
from cryptography.fernet import Fernet
# 使用Fernet对字符串进行AES加密和解密
key = Fernet.generate_key()
cipher_suite = Fernet(key)
plaintext = "Hello World"
cipher_text = cipher_suite.encrypt(plaintext.encode())
print(cipher_text)
decrypted_text = cipher_suite.decrypt(cipher_text)
print(decrypted_text.decode())
# 使用RSA生成公钥和私钥,并使用公钥加密和私钥解密
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()
plaintext = b"Hello World"
ciphertext = public_key.encrypt(
plaintext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(ciphertext)
decrypted_text = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(decrypted_text)
```
以上是一些常用的加密库及其示例用法,你可以根据自己的需求选择合适的库来实现加密。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)