models.py 2.6 KB
# coding=utf-8

import os
from flask_sqlalchemy import SQLAlchemy
import glob
import traceback
from pyDes import des, PAD_PKCS5, ECB
import json
import base64
from gmssl import sm3, func
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad, pad
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import algorithms
from binascii import b2a_hex, a2b_hex


class AESHelper():
    key = 'w03MyIgc3zMHM5Qe'.encode('utf-8')
    iv = '8765432187654321'.encode('utf-8')

    @classmethod
    def encode(self, instr):
        plaintxt = self._pad(instr)
        aes = AES.new(self.key, AES.MODE_CBC, self.iv)
        ciphertext = aes.encrypt(plaintxt)
        return b2a_hex(ciphertext).decode('utf-8')

    @classmethod
    def decode(self, instr):
        encryptedData = instr
        aes = AES.new(self.key, AES.MODE_CBC, self.iv)
        plaintxt = aes.decrypt(a2b_hex(encryptedData))
        return  bytes.decode(unpad(plaintxt, AES.block_size))

    def _pad(data):
        if not isinstance(data, bytes):
            data = data.encode()
        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data)+padder.finalize()
        return padded_data


class SM3():
    @classmethod
    def encode(self, data=""):
        by_str = bytes(data, 'utf-8')
        result = sm3.sm3_hash(func.bytes_to_list(by_str))
        return result


class DES():
    '''
    DES密码加解密
    '''
    Des: des = des("Chinadci", ECB, "\0\0\0\0\0\0\0\0",
                   pad=None, padmode=PAD_PKCS5)

    @classmethod
    def encode(cls, data):
        return str(base64.b64encode(cls.Des.encrypt(data)), encoding="utf8")

    @classmethod
    def decode(cls, data):
        if data:
            return str(cls.Des.decrypt(base64.b64decode(data.encode("utf-8"))), encoding="utf8")

        else:
            return data


db = SQLAlchemy()

# 动态加载Model
current_dir = os.path.abspath(os.path.dirname(__file__))
pkgs = list(glob.glob('%s/modules/*/models' % (current_dir)))
pkgs.extend(list(glob.glob('%s/modules/*/*/models' % (current_dir))))

for pkg in pkgs:
    pkg = os.path.normpath(pkg)
    node_list = pkg.split(os.path.sep)
    pkg_name = "app.{}".format(
        ".".join(node_list[node_list.index("modules"):]))
    try:
        if pkg_name.__contains__("models"):
            __import__(pkg_name)
    except Exception as e:
        print(traceback.format_exc())
        pass

if __name__ == '__main__':
    print(DES.decode("qnt136jlHF77l8+XaSHtbmMMbPdv7XeBPMyyUODlf0a8D0Lp+LurzZD+P8SdM76w0FrOkqGpLWtehsrYKjMQSQ=="))