python如何base64加解密
时间: 2023-07-19 21:55:33 浏览: 52
Python中可以使用base64模块对字符串进行加解密。具体方法如下:
1. 将字符串转换为bytes类型:
```python
str = "hello world"
bytes_str = str.encode("utf-8")
```
2. 对bytes类型进行加密:
```python
import base64
encode_str = base64.b64encode(bytes_str)
```
3. 将加密后的结果转换为字符串:
```python
encode_str = encode_str.decode("utf-8")
```
4. 对加密后的字符串进行解密:
```python
decode_str = base64.b64decode(encode_str)
```
5. 将解密后的结果转换为字符串:
```python
decode_str = decode_str.decode("utf-8")
```
完整代码:
```python
import base64
str = "hello world"
bytes_str = str.encode("utf-8")
encode_str = base64.b64encode(bytes_str)
encode_str = encode_str.decode("utf-8")
decode_str = base64.b64decode(encode_str)
decode_str = decode_str.decode("utf-8")
print("加密前的字符串为:", str)
print("加密后的字符串为:", encode_str)
print("解密后的字符串为:", decode_str)
```