接口自動化--數據加密之AES

在接口測試中,會遇到加密的請求數據,例如:經常使用的base64加密,AES加密,在這裏,簡述用Python轉化AES的加密方法html

原理

Python實現:Crypto算法庫

算法庫詳解: http://www.javashuo.com/article/p-duswtfre-gk.htmlpython

安裝 Crypto不是自帶的模塊,須要下載。http://www.voidspace.org.uk/python/modules.shtml#pycrypto算法

安裝好引用的時候,提示找不到Crypto,找了不少資料,緣由是 C:\Python27\Lib\site-packages在這個路徑下面有一個文件夾叫作crypto,把它的首字母改爲大寫,便是Crypto 就沒有問題了json

簡單使用

from Crypto.Cipher import AES 
import base64 
secret = "12345678912345678912345678912345"   #由用戶輸入的16位或24位或32位長的初始密碼字符串 
cipher = AES.new(secret)            #經過AES處理初始密碼字符串,並返回cipher對象 
s = cipher.encrypt("1234567891234567")     #輸入須要加密的字符串,注意字符串長度要是16的倍數。16,32,48.. 
print s                     #輸出加密後的字符串 
print base64.b64encode(s)            #輸出加密後的字符串的base64編碼。 
print cipher.decrypt(s)             #解密

接口自動化中實現

class AesMethod:
    def __init__(self):
        self.key=key
    def pkcs7padding(self,text):
        """
        明文使用PKCS7填充,若是塊長度是16,數據長度9,那麼還差7個字節,就在後面補充7個0x07
        數據:  FF FF FF FF FF FF FF FF FF
        填充後:FF FF FF FF FF FF FF FF FF 07 07 07 07 07 07 07
        最終調用AES加密方法時,傳入的是一個byte數組,要求是16的整數倍,所以須要對明文進行處理
        :param text: 待加密內容(明文)
        :return:填充後的數據
        """
        bs = AES.block_size  # 16
        length = len(text)
        bytes_length = len(bytes(text, encoding='utf-8'))
        # tips:utf-8編碼時,英文佔1個byte,而中文佔3個byte
        padding_size = length if(bytes_length == length) else bytes_length
        padding = bs - padding_size % bs
        # tips:chr(padding)看與其它語言的約定,有的會使用'\0'
        padding_text = chr(padding) * padding
        return text + padding_text

    def aes_encrypt(self, data):
        key_bytes=bytes(self.key, encoding='utf-8')
        cipher = AES.new(key_bytes,mode=1)
        # 處理明文
        content_padding = self.pkcs7padding(data)
        # 加密
        encrypt_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8'))
        # 從新編碼
        result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')
        return result
相關文章
相關標籤/搜索