python加密解密字符串
时间: 2023-12-31 17:02:40 浏览: 62
Python中可以使用多种方法进行字符串的加密和解密操作。
一种常见的方法是使用`base64`模块进行编码和解码。编码可以将一个字符串转换为一串由大小写字母、数字和特殊字符组成的编码字符串,解码则可以将编码字符串还原为原始字符串。
下面是一个使用`base64`模块进行加密解密的示例代码:
```python
import base64
def encrypt_string(input_string):
# 将字符串转换为字节流
bytes_string = input_string.encode('utf-8')
# 使用base64编码字节流
encrypted_bytes = base64.b64encode(bytes_string)
# 将编码字节流转换为字符串
encrypted_string = encrypted_bytes.decode('utf-8')
return encrypted_string
def decrypt_string(input_string):
# 将字符串转换为字节流
bytes_string = input_string.encode('utf-8')
# 使用base64解码字节流
decrypted_bytes = base64.b64decode(bytes_string)
# 将解码字节流转换为字符串
decrypted_string = decrypted_bytes.decode('utf-8')
return decrypted_string
# 测试加密和解密功能
original_string = 'Hello, World!'
encrypted_string = encrypt_string(original_string)
decrypted_string = decrypt_string(encrypted_string)
print('原始字符串:', original_string)
print('加密后的字符串:', encrypted_string)
print('解密后的字符串:', decrypted_string)
```
另一种常见的加密方法是使用`hashlib`模块进行哈希加密。哈希函数将一个字符串转换为固定长度的哈希值,且哈希值是不可逆的。这意味着无法通过哈希值还原出原始字符串,只能通过比对哈希值来验证字符串的正确性。
下面是一个使用`hashlib`模块进行哈希加密的示例代码:
```python
import hashlib
def encrypt_string(input_string):
# 创建一个哈希对象
hash_object = hashlib.sha256()
# 更新哈希对象的内容
hash_object.update(input_string.encode('utf-8'))
# 获取哈希值
encrypted_string = hash_object.hexdigest()
return encrypted_string
# 测试加密功能
original_string = 'Hello, World!'
encrypted_string = encrypt_string(original_string)
print('原始字符串:', original_string)
print('加密后的字符串:', encrypted_string)
```
需要注意的是,哈希加密是不可逆的,所以无法通过解密函数获取原始字符串。
相关推荐
![](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)