Python 實現AEC CBC 加密解密方式


安裝

python 在 Windows下使用AES時要安裝的是pycryptodome 模塊   pip install pycryptodome 

python 在 Linux下使用AES時要安裝的是pycrypto模塊   pip install pycrypto 

CBC加密需要一個十六位的key(密鑰)和一個十六位iv(偏移量)

介紹

使用AES加密,秘鑰key為36o%SituationSIS,被加密明文為用戶名+空格+密碼,用戶名不可包含空格

例:admin admin123

被加密的明文長度必須是key長度的整數倍,轉成16進制字符串,是因為aes為塊加密,如果要加密數據為不足塊大小或不為塊大小的整數倍數據時,就需要涉及填充和鏈加密模式,本次使用的CBC是一種循環模式,前一個分組的密文和當前分組的明文異或操作后再加密,這樣做的目的是增強破解難度,從網上找到一個比較容易理解的原理圖:

 

 

 

代碼

# -*- coding: utf-8 -*-
import base64
import logging

from Crypto.Cipher import AES


class AESCipher:
    """
    AES 工具類
    """

    def __init__(self, key, iv):
        # 只截取16位
        self.key = key[:16]
        # 16位字符,用來填充缺失內容,可固定值也可隨機字符串,具體選擇看需求
        self.iv = iv[:16]

    def __pad(self, text):
        """
        填充方式,加密內容必須為16字節的倍數,若不足則使用self.iv進行填充
        """
        text_length = len(text)
        amount_to_pad = AES.block_size - (text_length % AES.block_size)
        if amount_to_pad == 0:
            amount_to_pad = AES.block_size
        pad = chr(amount_to_pad)
        return text + pad * amount_to_pad

    def __unpad(self, text):
        pad = ord(text[-1])
        return text[:-pad]

    def encrypt(self, raw):
        """
        加密
        """
        raw = self.__pad(raw)
        print raw
        # 可以選擇加密方式
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return base64.b64encode(cipher.encrypt(raw))

    def decrypt(self, enc):
        """
        解密
        """
        enc = base64.b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return self.__unpad(cipher.decrypt(enc).decode("utf-8"))

def __unpad(text):
    pad = ord(text[-1])
    return text[:-pad]


if __name__ == '__main__':
    e = AESCipher('36o%SituationSIS', "36o%SituationSIS")
    secret_data = "admin admin123"
    enc_str = e.encrypt(secret_data)
    print('enc_str: ' + enc_str.decode())
    dec_str = e.decrypt(enc_str)
    print('dec str: ' + dec_str)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM