Python中字符串加密的方法有哪些
有的时候我们写的东西不想让别人看到,会设置密码来加密。在Python中,我们写的字符字符不想被别人看到,保护自己的隐私,会选择加密。本文介绍Python字符串加密的五种方法:url编码、base64、ascii、md5 Unicode转中文。具体代码如下:
1、url编码
from urllib.parse import quote, unqoutestring = '中国红'
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 base64s1 = 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'\\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"))
# 王大锤
# -*- coding: UTF-8 -*-
name = "asdzxc123"
# 编码
ascii_name = list(map(ord, name))
print(ascii_name)
# 解码
print("".join(map(chr, ascii_name)))
#!/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'\\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"))
# 王大锤
以上就是小编整理Python中给字符串加密的五种方法,是比较全面的,可以选择自己喜欢的方法去给字符串加密哦~
以上是 Python中字符串加密的方法有哪些 的全部内容, 来源链接: utcz.com/z/541739.html