【Python 3.6.1】Base64编码
首先明确一下,Base64编码并非“加密”,而是采用Base64编码具有不可读性,即所编码的数据不会被人用肉眼所直接看到,也就是我们常说的“防君子不防小人”的做法。
一、代码
|
1 |
[root@dt xxf]# vi base.py |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import base64 def enc(p_str): # base64 编码;这里需要注意,编码的字符串必须是二进制。(当然,无论是utf-8或是ascii或是gb2312均可) encodestr = base64.b64encode(bytes(p_str,'utf-8')) return encodestr.decode() def dec(p_str): #解码 decodestr = base64.b64decode(p_str) return decodestr.decode() # 交互式接收到输入的字符串 istr = input("Please enter a string:") # 通过enc自定义函数进行base64编码 bstr = enc(istr) # 打印编码后的字符串 print (bstr) # 解码,打印 ostr = dec(bstr) print (ostr) |
二、运行效果
|
1 2 3 4 5 |
[root@dt xxf]# python3 base.py Please enter a string:Hello World! SGVsbG8gV29ybGQh Hello World! [root@dt xxf]# |