python转换加密算法
时间: 2023-07-09 16:46:48 浏览: 66
Python提供了多种加密算法的库,可以根据不同的需求选择不同的算法。以下是几种常见的加密算法及其Python实现:
1. MD5加密算法
Python中使用hashlib库实现MD5加密算法,示例代码如下:
```python
import hashlib
def md5_encrypt(str):
m = hashlib.md5()
m.update(str.encode('utf-8'))
return m.hexdigest()
# 示例
print(md5_encrypt('hello world'))
```
2. SHA加密算法
Python中使用hashlib库实现SHA加密算法,示例代码如下:
```python
import hashlib
def sha_encrypt(str):
sha = hashlib.sha256()
sha.update(str.encode('utf-8'))
return sha.hexdigest()
# 示例
print(sha_encrypt('hello world'))
```
3. Base64加密算法
Python中使用base64库实现Base64加密算法,示例代码如下:
```python
import base64
def base64_encrypt(str):
return base64.b64encode(str.encode('utf-8')).decode('utf-8')
# 示例
print(base64_encrypt('hello world'))
```
4. RSA加密算法
Python中使用crypto库实现RSA加密算法,示例代码如下:
```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
# 生成RSA公钥和私钥
def generate_rsa_key():
rsa = RSA.generate(2048)
private_key = rsa.exportKey()
public_key = rsa.publickey().exportKey()
return private_key, public_key
# 使用RSA公钥加密
def rsa_encrypt(str, public_key):
rsa_key = RSA.importKey(public_key)
cipher = PKCS1_v1_5.new(rsa_key)
cipher_text = cipher.encrypt(str.encode('utf-8'))
return base64.b64encode(cipher_text).decode('utf-8')
# 使用RSA私钥解密
def rsa_decrypt(encrypt_str, private_key):
rsa_key = RSA.importKey(private_key)
cipher = PKCS1_v1_5.new(rsa_key)
cipher_text = base64.b64decode(encrypt_str)
return cipher.decrypt(cipher_text, None).decode('utf-8')
# 示例
private_key, public_key = generate_rsa_key()
encrypt_str = rsa_encrypt('hello world', public_key)
decrypt_str = rsa_decrypt(encrypt_str, private_key)
print(encrypt_str)
print(decrypt_str)
```
以上是部分加密算法的Python实现,具体应用根据需求选择相应的算法即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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://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)