zoukankan      html  css  js  c++  java
  • python aes_cbc加密

    from Crypto.Cipher import AES

    # aes加密解密 def pkcs7padding(self,text): """ 明文使用PKCS7填充 最终调用AES加密方法时,传入的是一个byte数组,要求是16的整数倍,因此需要对明文进行处理 :param text: 待加密内容(明文) :return: """ bs = AES.block_size # 16 length = len(text) bytes_length = len(bytes(text, encoding='utf-8')) # tips:utf-8编码时,英文占1个byte,而中文占3个byte padding_size = length if (bytes_length == length) else bytes_length padding = bs - padding_size % bs # tips:chr(padding)看与其它语言的约定,有的会使用'' padding_text = chr(padding) * padding return text + padding_text def pkcs7unpadding(self,text): """ 处理使用PKCS7填充过的数据 :param text: 解密后的字符串 :return: """ length = len(text) unpadding = ord(text[length - 1]) return text[0:length - unpadding] def aescode(self, type_, str_): thirdpass_key = b'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' thirdpass_iv = b'aaaaaaaaaaaaaaaa' key = thirdpass_key # 32bytes iv = thirdpass_iv # 还需要使用iv一个向量. # 使用key和iv初始化AES对象, 使用MODE_CFB模式. try: aesobj = AES.new(key, AES.MODE_CBC, iv) except Exception as e: return (False, 'aes初始化失败') try: if type_ == 'encode': # 处理明文 content_padding = self.pkcs7padding(str_) data_str = content_padding.encode("utf-8") aesencode = base64.b64encode(aesobj.encrypt(data_str)).decode() return (True, aesencode) elif type_ == 'decode': # 处理明文 data_str = str_.encode("utf-8") aesdecode = aesobj.decrypt(base64.b64decode(data_str)).decode() aesdecode = self.pkcs7unpadding(aesdecode) return (True, aesdecode) else: return (False, 'type_ is encode/decode') except Exception as e: return (False, 'aes方法报错')

    [True, 'CCAVPBaD6gptwAeGwtC0Rw==']
    (True, '{"k": "a"}'

  • 相关阅读:
    linux下实现nginx反向代理
    linux下实现nginx安装实现端口区分,域名区分
    redis整合spring
    linux下安装redis以及redis集群
    Kindeditor编辑器
    ActiveMQ
    redis(保存邮件激活码)
    AngularJS (验证码倒计时)
    linux部署项目(oracle+redis+activeMQ+elasticSearch+tomcat+JDK8)
    WebService
  • 原文地址:https://www.cnblogs.com/zhangkui/p/12965876.html
Copyright © 2011-2022 走看看