AES加密——python實現

簡介

高級加密標準(英語:Advanced Encryption Standard,縮寫:AES),在密碼學中又稱Rijndael加密法,是美國聯邦政府採用的一種區塊加密標準。這個標準用來替代原先的DES,已經被多方分析且廣爲全世界所使用。經過五年的甄選流程,高級加密標準由美國國家標準與技術研究院(NIST)於2001年11月26日發佈於FIPS PUB 197,並在2002年5月26日成爲有效的標準。2006年,高級加密標準已然成爲對稱密鑰加密中最流行的算法之一。

代碼

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex  # 處理位數
from Crypto import Random


class PrpCrypt(object):
    def __init__(self, key):
        """
        初始化方法
        :param key:
        """
        self.key = key.encode('utf-8')  # 先將傳進來的數據進行編碼,utf-8是目前互聯網中使用最爲廣泛的一種
        self.mode = AES.MODE_CBC  # 根據要求返回的數據,選擇對應的算法,這裏mode-cbc返回的是2
        self.iv = Random.new().read(AES.block_size)  # 隨機生成十六進制數字 讀取處理的數據

    def encrypto(self, text):
        """
        加密函數 如果text不足16位就使用空格來補足16位(16位 密鑰規則)
        :return:統一加密後的字符串轉換成16進制後的字符串
        """
        text = text.encode('utf-8')
        cryptor = AES.new(self.key, self.mode, self.iv)
        # 密鑰長度   AES-128(16)    AES-192(24)     AES-256(32)     Bytes 長度
        length = 16
        # 用戶輸入的字符串長度
        count = len(text)
        if count < length:
            add = (length - count)
            text = text + ('\0' * add).encode('utf-8')
        elif count > length:
            add = (length - (count % length))
            text = text + ('\0' * add).encode('utf-8')

        self.ciphertext = cryptor.encrypt(text)  # 加密
        return b2a_hex(self.ciphertext)  # 返回16進制加密結果

    def dencrypto(self, text):
        """
        解密函數
        :return:
        """
        cryptor = AES.new(self.key, self.mode, self.iv)
        plain_text = cryptor.decrypt(a2b_hex(text))
        return bytes.decode(plain_text).rstrip('\0')  # rstrip去除空格,decode將二進制反編碼爲str

if __name__ == '__main__':  # 程序入口
    i = 1
    while i:
        judge = input('加密請輸入1,解密請輸入2:')
        if judge == '1':
            keys = input('請輸入16位長度的加密密鑰:')
            pc = PrpCrypt(keys)
            data = input('請輸入你要加密的數據:')
            e = pc.encrypto(data)  # 加密
            print('加密', e)
        elif judge == '2':
            # key2 = input('請輸入16位長度的解密密鑰:')
            # pc = PrpCrypt(key2)
            data2 = input('請輸入你需要解密的數據:')   # 解密encode編碼
            d = pc.dencrypto(data2).encode()
            #d = pc.dencrypto(e).encode()
            #d = pc.dencrypto(b2a_hex(data2)).encode()   #Data must be padded to 16 byte boundary in CBC mode
            print('解密', d)

運行示例

在這裏插入圖片描述

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