简单实用的加密算法

 代码

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from django.conf import settings


class Cryptography:
    def __init__(self, key=None):
        self.key = key or settings.PASSWORD_KEY
        self.mode = AES.MODE_ECB
        self.cryptor = AES.new(self.pad(self.key).encode(), self.mode)

    # 加密函数,如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数
    @staticmethod
    def pad(text):
        # 加密内容需要长达16位字符,所以进行空格拼接
        while len(text) % 16 != 0:
            text += ' '
        return text

    def encrypt(self, text):
        # 这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用
        # 加密的字符需要转换为bytes
        # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
        # 所以这里统一把加密后的字符串转化为16进制字符串
        return b2a_hex(self.cryptor.encrypt(self.pad(text).encode())).decode()

    def decrypt(self, text):
        # 解密后,去掉补足的空格用strip() 去掉
        res = self.cryptor.decrypt(a2b_hex(text))
        return res.decode().strip(' ')

    # 判断value是否是加密后的值
    def check_can_decrypt(self, value):
        try:
            de_p = self.decrypt(value)
            return True, de_p
        except ValueError:
            return False, None
        except Exception as e:
            print('解密错误:', e)
            return False, None


if __name__ == '__main__':
    pc = Cryptography("AAAA")  # 初始化密钥

    e = pc.encrypt("0123456789ABCDEF")
    d = pc.decrypt(e)
    print(e, d)
    print(pc.check_can_decrypt(e))
    print(pc.check_can_decrypt(d))

    e = pc.encrypt("00000000000000000000000000")
    d = pc.decrypt(e)
    print(e, d)

 结果

184a7d838b1f9a412698f4d521a552ad 0123456789ABCDEF
(True, '0123456789ABCDEF')
(False, None)
a995f56eccacc8e84ec136e6756308dcb7e0944380ce13aab1eb06f8aab85a86 00000000000000000000000000

本文来自博客园,作者:羊驼之歌,转载请注明原文链接:https://www.cnblogs.com/shijieli/p/15160579.html

原文地址:https://www.cnblogs.com/shijieli/p/15160579.html