Python AES encryption instance resolution

  • 2020-07-21 08:51:06
  • OfStack

This paper mainly makes a brief analysis of aes encryption technology, and then USES Python implementation, which is described as follows.

AES is a kind of encryption technology adopted by the US federal government. AES has several modes, among which CBC mode is recognized as the most secure mode and is adopted by TLS.

The encryption and decryption sides need to determine key, the length of key can be 16 bits, 24 bits, 32 bits, corresponding to different algorithms.

If key is 16 bits long, the encrypted plaintext must be an integer multiple of 16, but in practice, such a coincidence is difficult to happen, so you need to fill the plaintext, the most common way is to fill \0, wait until decryption, then decrypt the decrypted plaintext to the right of all \0. Now, you might be concerned that if I have 1 heap of \0 on the far right of the plaintext, then I'm going to have a problem with this, yeah, it's going to be a problem, but what is this plaintext doing? You think too much, you will never encounter such a clear text in your life.

Here is a sample python code to demonstrate how to use AES encryption for encryption and decryption


#coding=utf-8 
''''' 
 encrypted 1 Square and decrypted 1 We must make sure in advance key value  
''' 
from Crypto.Cipher import AES 
from binascii import b2a_hex, a2b_hex 
 
class MyCrypto(): 
  def __init__(self, key): 
    self.key_len = len(key) 
    if not self.key_len == 16 and not self.key_len == 24 and not self.key_len == 32: 
      raise Exception("length of key is wrong") 
    self.key = key 
    self.mode = AES.MODE_CBC  # This model is safer  
 
  def encrypt(self, text): 
    ''''' 
       The length of the encrypted clear text must be key An integer multiple of length , If not enough , To use \0 To fill  
       into 16 Base string , It's to avoid the invisible ascii Misbehave while displaying  
    ''' 
    cryptor = AES.new(self.key, self.mode, self.key) 
    count = len(text) 
    add = self.key_len - (count % self.key_len) 
    text = text + ('\0' * add) 
    self.ciphertext = cryptor.encrypt(text) 
    return b2a_hex(self.ciphertext) 
 
 
  def decrypt(self, text): 
    ''''' 
       Note after decryption , It is possible to populate the encryption \0, So we want to get rid of the right-hand side \0 
    ''' 
    cryptor = AES.new(self.key, self.mode, self.key) 
    plain_text = cryptor.decrypt(a2b_hex(text)) 
    return plain_text.rstrip('\0') 
 
 
if __name__ == '__main__': 
  mc = MyCrypto("kwsy_zds20160822") 
  e = mc.encrypt(" Dong-sheng zhang ") 
  d = mc.decrypt(e) 
  print e,d 

conclusion

That is the end of this article on Python AES encryption instance parsing, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: