python3.x实现base64加密和解密

用python3.x实现base64加密和解密,供大家参考,具体内容如下

加密

base64_encrypt.py

#!/usr/bin/python3
#encoding:utf-8
import base64
var = 1
while var==1:
  str_encrypt=input("输入要加密的字符串:\n"); 
  base64_encrypt = base64.b64encode(str_encrypt.encode('utf-8'))
  print("BASE64加密串:\n"+str(base64_encrypt,'utf-8'))
  print("按ctrl+c退出程序")

打开windows命令窗口>把加密代码文件拖入黑窗口>回车>输入要加密的字符串>回车完成加密

解密

base64_decrypt.py

#!/usr/bin/python3
#encoding:utf-8
import base64
import logging
import sys
'''
方式一:简单的logger配置
log_file = "E:\pythonwork/basic_logger.log"
logging.basicConfig(filename = log_file, level = logging.INFO)
'''

#方式二
#用base64_decrypt创建日志记录器
logger = logging.getLogger('base64_decrypt')
logger.setLevel(logging.DEBUG)
#创建甚至记录调试消息的文件处理程序
fh = logging.FileHandler("E:\pythonwork/basic_logger.log")
fh.setLevel(logging.DEBUG)
#创建具有较高日志级别的控制台处理程序
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
#创建格式化程序并将其添加到处理程序中
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
#将处理程序添加到记录器
logger.addHandler(fh)
logger.addHandler(ch)


while True :
  global base64_decrypt
  try:
    str_decrypt=input("输入BASE64加密串:\n")
    base64_decrypt = base64.b64decode(str_decrypt.encode('utf-8'))
    print("BASE64解密串(UTF-8):\n",str(base64_decrypt,'utf-8'))
    logger.info("BASE64解密串:\n"+str(base64_decrypt,'utf-8'))
  except Exception as e:
    print ("BASE64解密串(UTF-8)异常:", e)
    print("BASE64解密串(默认字符集):\n",str(base64_decrypt))
    base64_decrypt=""
    logger.info("e:"+ str(e))
  finally: 
    print("按ctrl+c退出程序")

打开windows命令窗口>把解密代码文件拖入黑窗口>回车>输入要解密的字符串>回车完成解密

相关推荐