天天看點

python3的aes算法實作

調用pycryptodome庫中的aes,實作加密解密

#/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import base64
import binascii

def create_key(key):
    n = len(key)
    if n > 32:
        key = key[0:32]
    elif n > 16:
        key = key + '\0' * (8 - (n%8))
    elif n < 16:
        key = key + '\0' * (16 - (n%16))
    return key.encode('utf-8')

class _aes():
    def __init__(self,key):
        self.key = create_key(key)
        self.mode = AES.MODE_CBC
        self.iv = self.key[0:16]

    def set_key(self,new_key):
        self.key = create_key(new_key)
        self.iv = self.key[0:16]

    def encrypt(self,code):
        cipher = AES.new(self.key, self.mode, self.iv)
        n = 16
        l = len(code)
        if l % n != 0:
            code = code + ('\0' * (16 - (l%16)))
        code = code.encode('utf-8')
        encode = cipher.encrypt(code)  
        return base64.encodebytes(encode)  # base64 encode

    def decode(self,encode):
        cipher = AES.new(self.key, self.mode, self.iv)
        code = cipher.decrypt(base64.decodebytes(encode))
        return (code.decode('utf-8')).rstrip('\0')