python2.7 AES 加解密(工具類)

先安裝包

pip install pycrypto==2.6.1

加解密類

# coding=utf-8
from Crypto.Cipher import AES


class ASEUtil(object):
    """
    ase加解密工具類
    """

    @staticmethod
    def encrypt(key, text):
        """
        解密
        """
        bs = AES.block_size

        def pad(s): return s + (bs - len(s) % bs) * chr(bs - len(s) % bs)

        cipher = AES.new(key, AES.MODE_ECB)  # ECB模式
        return cipher.encrypt(pad(text)).encode("hex")

    @staticmethod
    def decrypted(key, cipher_text):
        """
        解密
        """
        cipher = AES.new(key, AES.MODE_ECB)  # ECB模式

        def un_pad(s): return s[0:-ord(s[-1])]

        return un_pad(cipher.decrypt(cipher_text.decode("hex")))


if __name__ == '__main__':
    encrypt = ASEUtil.encrypt('hhhhhhhhhhhhhhhh', '{"abc":"abc"}')
    decrypted = ASEUtil.decrypted('hhhhhhhhhhhhhhhh',encrypt)
    print(decrypted)

該代碼僅支持python2,注意,key只能爲16位或者16位的倍數,否則報錯

ValueError: Incorrect AES key length (15 bytes)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章