python AES symmetric encryption

1, you first need to install third-party libraries

  pip install pycryptodome

2, example code, pro-test available

# Coding: UTF. 8- 

Import Base64
 from Crypto.Cipher Import AES 


class USE_AES:
     "" " 
    AES 
    addition MODE_SIV mode key length: 32, 48, or 64, 
    the remaining length of key 16, 24 or 32 
    in detail within the document, see AES 
    CBC mode iv parameters passed 
    according to the present embodiment using common ECB mode 
    "" " 

    DEF  the __init__ (Self, Key):
         IF len (Key)> 32 : 
            Key = Key [: 32 ] 
        self.key = self.to_16 (Key) 

    DEF to_16 (Self, Key):
         "" " 
        Switch to a multiple of 16 bytes of data  
        : param key:
        : return: 
        """
        key = bytes(key, encoding="utf8")
        while len(key) % 16 != 0:
            key += b'\0'
            print("to_16")
        return key  # 返回bytes

    def aes(self):
        return AES.new(self.key, AES.MODE_ECB) # 初始化加密器

    def encrypt(self, text):
        aes = self.aes()
        return str(base64.encodebytes(aes.encrypt(self.to_16(text))),
                   encoding='utf8').replace('\n', '')  # 加密

    def decodebytes(self, text):
        aes = self.aes()
        return str(aes.decrypt(base64.decodebytes(bytes(
            text, encoding='utf-8'))).rstrip(b'\0').decode("utf-8"))  # 解密


if __name__ == '__main__':
    # aes_test = USE_AES("e9abe30a15422ae73bc39aa89ccd75d52f72c3ff")
    aes_test = USE_AES("e9fc52c72346ecc9")
    encrypt = aes_test.encrypt('{"data":{"type":"html","mobile":"17100000002"}}')
    decode = aes_test.decodebytes('TVaxmOv920UbPyV7NVDbv5ApDPzaL3P4w3MC8b2XvxqHUCwAi58m0D2IR+f7wrmH')
    print(encrypt)
    print(decode)

 

Guess you like

Origin www.cnblogs.com/yaoqingzhuan/p/11121141.html