Python中字符串加密的方法有哪些?
732次观看1、url编码
from urllib.parse import quote, unqoute
string = '中国红'
en_str = 'hello'
# 编码
utf8_code = quote(string) # 默认编码格式是utf-8
print(utf8_code)
# 输出结果: %E4%BD%A0%E5%A5%BD%E5%95%8A
en_code = quote(en_str)
print(en_code)
# 输出结果: hello !当传入的字符串不是中文时,这个编码会原文输出
# 设置编码格式
gbk_code = quote(string, encoding='gbk')
print(gbk_code)
# 输出: %E4%BD%A0%E5%A5%BD%E5%95%8A
# 解码
prot_str = unquote(gbk_code, encoding='gbk')
print(prot_str)
# 输出结果: 中国红
2、base64(最简单但保密度不高)
import base64
s1 = base64.encodestring('hello world')
s2 = base64.decodestring(s1)
print s1,s2
# aGVsbG8gd29ybGQ=n
# hello world
3、ascii
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
name = "asdzxc123"
# 编码
ascii_name = list(map(ord, name))
print(ascii_name)
# 解码
print("".join(map(chr, ascii_name)))
4、md5
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Nick
# @Date: 2019-10-24 10:24:32
# @Last Modified by: Nick
# @Last Modified time: 2019-10-24 10:50:45
def md5_encode(original_str):
"""
功能:实现字符串 md5加密
:param original_str:
:return:
"""
m = hashlib.md5()
m.update(original_str.encode(encoding='UTF-8'))
return m.hexdigest()
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'u738bu5927u9524'
print(utf8_name)
# b'xe7x8ex8bxe5xa4xa7xe9x94xa4'
print(gbk_name)
# b'xcdxf5xb4xf3xb4xb8'
print(gbk2312_name)
# b'xcdxf5xb4xf3xb4xb8'
# 解码
print(unicode_name.decode())
# u738bu5927u9524
print(unicode_name.decode("unicode_escape"))
# 王大锤
print(utf8_name.decode()) # 默认utf-8
# 王大锤
print(gbk_name.decode("gbk"))
# 王大锤
©本文版权归环球青藤所有,任何形式转载请联系我们。