Python 對字串 加密 的5種方式
阿新 • • 發佈:2018-12-16
本文中的加密,是指人不能直觀看出資訊的加密 即:肉眼不可見的加密
1. url編碼
from urllib.parse import quote, unquote
name = "王大錘"
# 編碼
utf8_name = quote(name) # utf-8
print(utf8_name)
# %E7%8E%8B%E5%A4%A7%E9%94%A4 長度是 9
gbk_name = quote(name, encoding="gbk")
print(gbk_name)
# %CD%F5%B4%F3%B4%B8 長度是 6
# 解碼
print(unquote(utf8_name) )
print(unquote(gbk_name, encoding="gbk"))
# 王大錘
- Base64編碼
# base64編碼是將二進位制位元組流編碼為可列印的64個字元
# 以6位分割 bit位都是0,base64約定以‘=’代替
# z -> b'eg=='
import base64
name = "王大錘"
# 編碼: 字串 -> 二進位制 -> base64編碼
b64_name = base64.b64encode(name.encode())
print(b64_name)
# b'546L5aSn6ZSk'
# 解碼:base64編碼 -> 二進位制 -> 字串
print(base64.b64decode(b64_name).decode())
# 王大錘
3. 字串轉換ascii
name = "王大錘"
# 編碼
ascii_name = list(map(ord, name))
print(ascii_name)
# [29579, 22823, 38180]
# 解碼
print("".join(map(chr, ascii_name)))
# 王大錘
4. md5不可逆
解密推薦去cmd5
import hashlib
name = "王大錘"
# 編碼
print(hashlib.md5(name.encode()).hexdigest( ))
# 59c22c7bb43b8561cfd3b52f507171cb
5. Unicode轉中文
name = "王大錘"
# 編碼
unicode_name = name.encode("unicode_escape")
utf8_name = name.encode("utf-8")
gbk_name = name.encode("gbk")
gbk2312_name = name.encode("gb2312")
print(unicode_name)
# b'\\u738b\\u5927\\u9524'
print(utf8_name)
# b'\xe7\x8e\x8b\xe5\xa4\xa7\xe9\x94\xa4'
print(gbk_name)
# b'\xcd\xf5\xb4\xf3\xb4\xb8'
print(gbk2312_name)
# b'\xcd\xf5\xb4\xf3\xb4\xb8'
# 解碼
print(unicode_name.decode())
# \u738b\u5927\u9524
print(unicode_name.decode("unicode_escape"))
# 王大錘
print(utf8_name.decode()) # 預設utf-8
# 王大錘
print(gbk_name.decode("gbk"))
# 王大錘