Python中字符串加密的方法有哪些

发布时间:2022-05-18 09:44:29 人气:2130 作者:多测师

  有的时候我们写的东西不想让别人看到,会设置密码来加密。在Python中,我们写的字符字符不想被别人看到,保护自己的隐私,会选择加密。本文介绍Python字符串加密的五种方法:url编码、base64、ascii、md5 Unicode转中文。具体代码如下:

  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)

  # 输出结果: 中国红

Python中字符串加密的方法有哪些

  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'\\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相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线