Base64编码是一种“防君子不防小人”的编码方式。广泛应用于MIME协议,作为电子邮件的传输编码,生成的编码可逆,后一两位可能有“=”,生成的编码都是ascii字符。
优点:速度快,ascii字符,肉眼不可理解
缺点:编码比较长,非常容易被破解,仅适用于加密非关键信息的场合
In [3]: import os
In [5]: import base64
In [6]: s = os.urandom(64)
In [7]: SECRETY_KEY = base64.b64encode(s)
In [8]: print(SECRETY_KEY)
b'VKXV/D7japENU5OcH+40gvd/1RyfBV9OSbll71twKAK1xfmFNgxPscfmvawR8LYQGIrl1mpiT4tBTmdbKVyHqg=='
base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z, a-z, 0-9, +, /* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.
Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b’’ syntax.
If you remove the b, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it’s not 8-bit. It’s not really any bits, in fact. ?
import base64
def stringToBase64(s):
return base64.b64encode(s.encode('utf-8'))
def base64ToString(b):
return base64.b64decode(b).decode('utf-8')
quickly generate a value for Flask.secret_key (or SECRET_KEY):
$ python -c 'import os; print(os.urandom(16))'
b'_5#y2L"F4Q8z\n\xec]/'
# man base64
Base64 encode or decode FILE, or standard input, to standard output.
With no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
-d, --decode
decode data
-i, --ignore-garbage
when decoding, ignore non-alphabet characters
-w, --wrap=COLS
wrap encoded lines after COLS character (default 76). Use 0 to disable line
wrapping
--help display this help and exit
--version
output version information and exit
The data are encoded as described for the base64 alphabet in RFC 4648. When decoding, the
input may contain newlines in addition to the bytes of the formal base64 alphabet. Use
--ignore-garbage to attempt to recover from any other non-alphabet bytes in the encoded
stream.
格式:base64
从标准输入中读取数据,按Ctrl + D结束输入。将输入的内容编码为base64字符串输出。
格式:echo
“str” | base64
将字符串str + 换行
编码为base64字符串输出。
格式:echo - n
“str” | base64
将字符串str编码为base64字符串输出。
格式:base64
file
从指定的文件file中读取数据,编码为base64字符串输出。
➜ ~ base64
hello
aGVsbG8K
➜ ~ echo "hello" | base64
aGVsbG8K
格式:base64 - d
从标准输入中读取已经进行base64编码的内容,解码输出。
格式:base64 - d - i
从标准输入中读取已经进行base64编码的内容,解码输出。加上 - i参数,忽略非字母表字符,比如换行符。
格式:echo
“str” | base64 - d
将base64编码的字符串str + 换行
解码输出。
格式:echo - n
“str” | base64 - d
将base64编码的字符串str解码输出。 注意与上面的差别。
格式:base64 - d
file
从指定的文件file中读取base64编码的内容,解码输出。
➜ ~ base64 -d
aGVsbG8K
hello
➜ ~ echo "aGVsbG8K" | base64 -d
hello
import os
os.system(''' echo -n "aGVsbG8K" | base64 -d ''')