Interface Automation - Data encryption of AES

In the test the interface, will encounter encrypted request data, for example: base64 commonly used encryption, AES encryption, where encryption AES outlined in Python conversion

principle

  • Official website link: https://pycryptodome.readthedocs.io/en/latest/src/cipher/aes.html
  • Online encryption / decryption: https://www.sojson.com/encrypt_aes.html
  • AES encryption involves two main steps: plaintext encryption and key expansion.
    Key Expansion: key (16 bytes, 24 bytes and 32 bytes) extended input, depending on the key length, the key is extended not be the same number of rounds of encryption, the individual is understood to complement.
  •   例如:对用户名进行AES加密,6位的用户名不满足16个字节,就需要补充位数。


    Python implementation: Crypto algorithms library

Detailed algorithms library: https://segmentfault.com/a/1190000016851912

Installation
Crypto is not a built-in module, you need to download. http://www.voidspace.org.uk/python/modules.shtml#pycrypto

When installing the reference, suggesting no Crypto, find a lot of information, because the
C: \ Python27 \ Lib \ site -packages in following this path have a folder named crypto, it changed the first letter capitalized, that is, Crypto is
no problem

Simple to use

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)             #解密

Interface Automation achieved

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

Guess you like

Origin www.cnblogs.com/Testking/p/11991153.html