• Crypto 加密解密


    import binascii
    from Crypto.Cipher import AES
    #秘钥,此处需要将字符串转为字节
    from utils import config
    from utils.env_operation import conf_parse
    
    key = b'abcdefgh'
    #加密内容需要长达16位字符,所以进行空格拼接
    class crypt_util():
        def __init__(self):
            self.token = config.get_env('crypt_token').encode('utf-8')
            self.aes = AES.new(self.token, AES.MODE_CBC,b'0000000000000000')
    
        def encrypt(self,text):
            text = text.encode('utf-8')
            # 这里密钥key 长度必须为16(AES-128),
            # 24(AES-192),或者32 (AES-256)Bytes 长度
            # 目前AES-128 足够目前使用
            length = 16
            count = len(text)
            if count < length:
                add = (length - count)
                #  backspace
                # text = text + ('' * add)
                text = text + ('' * add).encode('utf-8')
            elif count > length:
                add = (length - (count % length))
                # text = text + ('' * add)
                text = text + ('' * add).encode('utf-8')
            self.ciphertext = self.aes.encrypt(text)
            # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
            # 所以这里统一把加密后的字符串转化为16进制字符串
            return binascii.b2a_hex(self.ciphertext)
    
    
    
        def decrypt(self,str):
            plain_text = self.aes.decrypt(binascii.a2b_hex(str))
            # return plain_text.rstrip('')
            print(bytes.decode(plain_text).rstrip(''))
            return bytes.decode(plain_text).rstrip('')
    
            # # a = b'8fea87a50aa6203cfcfd508fa30f8fa0d8cd103e3a37ef057f7763eff7742b51'
            # # 用aes对象进行解密,将字节类型转为str类型,错误编码忽略不计
            # de = self.aes.decrypt(binascii.a2b_hex(str)), encoding='utf-8', errors="ignore")
            # # 获取str从0开始到文本内容的字符串长度。
            # print(de)
            # return de
    
        def pad(text):
            while len(text) % 16 != 0:
                text += b' '
            return text
        #加密秘钥需要长达16位字符,所以进行空格拼接
        def pad_key(key):
            while len(key) % 16 != 0:
                key += b' '
            return key
    if __name__ == '__main__':
        conparse = conf_parse()
        conparse.confparse(vars)
        crypt=crypt_util()
        # print(crypt.encrypt("12345678"))
        crypt.decrypt('a56586aa860f83d6ba9a826b4c6df564')
  • 相关阅读:
    蛋疼的时候写三消游戏(三)
    Unity3d做的小游戏Demo《高铁惊魂》
    蛋疼的时候写三消游戏(四)
    Unity中调用http请求
    Unity中的单例
    Unity的IOS接入新浪微博
    Unity中实现热浪效果
    Unity开发摘要
    蛋疼的时候写三消游戏(二)
    蛋疼的时候写三消游戏(一)
  • 原文地址:https://www.cnblogs.com/paisen/p/10558644.html
Copyright © 2020-2023  润新知