pythonbase64加解密
时间: 2023-12-08 13:39:40 浏览: 35
以下是Python中使用base64进行加解密的示例:
1. 加密字符串
```python
import base64
# 将字符串转换为bytes类型
str = 'hello world'
str_bytes = str.encode('utf-8')
# 对bytes类型进行base64编码
enc_bytes = base64.b64encode(str_bytes)
# 将bytes类型转换为字符串
enc_str = enc_bytes.decode('utf-8')
print(enc_str) # 输出:aGVsbG8gd29ybGQ=
```
2. 解密字符串
```python
import base64
# 将字符串转换为bytes类型
enc_str = 'aGVsbG8gd29ybGQ='
enc_bytes = enc_str.encode('utf-8')
# 对bytes类型进行base64解码
dec_bytes = base64.b64decode(enc_bytes)
# 将bytes类型转换为字符串
dec_str = dec_bytes.decode('utf-8')
print(dec_str) # 输出:hello world
```
相关问题
python base64加密解密
Base64是一种常用的编码方式,可以将二进制数据转换为可打印的ASCII字符。在Python中,可以使用`base64`模块进行Base64编码和解码操作。
要进行Base64编码,可以使用`base64.b64encode()`函数。示例如下:
```python
import base64
data = b'Hello World' # 要进行编码的二进制数据
encoded_data = base64.b64encode(data)
print(encoded_data) # 输出编码后的数据
```
要进行Base64解码,可以使用`base64.b64decode()`函数。示例如下:
```python
import base64
encoded_data = b'SGVsbG8gV29ybGQ=' # 要进行解码的Base64数据
decoded_data = base64.b64decode(encoded_data)
print(decoded_data) # 输出解码后的二进制数据
```
需要注意的是,编码前的数据应为二进制类型,而解码后的数据是以二进制形式返回的。如果需要将解码后的二进制数据转换为字符串,可以使用`.decode()`方法。
希望对你有所帮助!如果你还有其他问题,请随时提问。
python如何base64加解密
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)
```