Usage analysis of Python AES encryption module

  • 2020-06-01 10:11:57
  • OfStack

This article illustrates the use of the Python AES encryption module as an example. I will share it with you for your reference as follows:

AES is a new encryption module. Last time I showed you how to use DES in OpenSSL. This time we'll take a look at how Python's own library USES AES for encryption and decryption. In fact, the principle of python is still very similar, except that it is easier to do this in python than C, but it is still a bit more verbose than C#/Java. In the language C#/JAVA, padding1 generally has a full implementation of the processing of encrypted source data. I dealt with this last time in the C language. In the python library, you need to handle this yourself.


from Crypto.Cipher import AES
# padding algorithm 
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(0)
unpad = lambda s : s[0:-ord(s[-1])]
#  Converts a string to 2 Into the system buff block 
def parse_hex(hex_str):
 l=int(math.ceil(len(hex_str)/2))
 buf=''
 for i in range(0,l):
  s=hex_str[(i*2):((i+1)*2)]
  buf=buf+chr(int(s,16))
 return buf
#  Analytically encrypted key
key=parse_hex("68b329da9893e34099c7d8ad5cb9c940")
iv=parse_hex("68b329da9893e34099c7d8ad5cb9c940")
#  new 1 a AES The object of 
aes_obj = AES.new(key, AES.MODE_CBC,iv)
#  Do byte alignment 
padding_zero=pad(raw_buf)
#  Began to encrypt 
encrypt_buf=aes_obj.encrypt(padding_zero)
#  decryption 
buff=aes_obj.decrypt(encrypt_buf)

padding in this code is still very nice. If you were to implement this in C, you'd have to write a lot more.

PS: about encryption and decryption interested friends can also refer to the website online tools:

Text online encryption and decryption tools (including AES, DES, RC4, etc.) :
http://tools.ofstack.com/password/txt_encode

MD5 online encryption tool:
http://tools.ofstack.com/password/CreateMD5Password

Online hash/hash algorithm encryption tool:
http://tools.ofstack.com/password/hash_encrypt

MD5/hash/ SHA-1 / SHA-2 / SHA-256 / SHA-512 / SHA-3 / RIPEMD-160 encryption tools:
http://tools.ofstack.com/password/hash_md5_sha

Online sha1 sha224 / sha256 sha384 / sha512 encryption tools:
http://tools.ofstack.com/password/sha_encode

More about Python related topics: interested readers to view this site "Python coding skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article is helpful for you to design Python program.


Related articles: