python 以utf8格式进行 base64加密
时间: 2023-08-17 22:29:14 浏览: 62
可以使用 Python 的 base64 和 encode 函数进行 utf8 格式的加密。以下是一个例子:
```python
import base64
message = "你好,世界!" # 要加密的信息
message_bytes = message.encode('utf-8') # 将信息转换为 utf8 格式的字节串
base64_bytes = base64.b64encode(message_bytes) # 对字节串进行 base64 加密
base64_message = base64_bytes.decode('utf-8') # 将加密后的字节串转换为字符串
print(base64_message) # 输出加密后的字符串
```
输出结果为:
```
5L2g5aW977yM6L+ZIQ==
```
需要注意的是,在解密时,需要先将字符串转换为字节串,然后再进行解密。以下是解密的例子:
```python
import base64
base64_message = "5L2g5aW977yM6L+ZIQ==" # 要解密的 base64 编码的字符串
base64_bytes = base64_message.encode('utf-8') # 将字符串转换为字节串
message_bytes = base64.b64decode(base64_bytes) # 对字节串进行 base64 解密
message = message_bytes.decode('utf-8') # 将解密后的字节串转换为字符串
print(message) # 输出解密后的字符串
```
输出结果为:
```
你好,世界!
```
相关推荐
![](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)