怎么在Python中实现AES加密
更新:HHH   时间:2023-1-7


怎么在Python中实现AES加密?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

Python主要用来做什么

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

#coding=utf-8 
''''' 
加密的一方和解密的一方必须提前确定好key值 
''' 
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  #这种模式更加安全 
 
  def encrypt(self, text): 
    ''''' 
      被加密的明文长度必须是key长度的整数倍,如果不够,则用\0进行填充 
      转成16进制字符串,是因为避免不可见的ascii在显示的时候捣乱 
    ''' 
    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): 
    ''''' 
      解密后需注意,加密时有可能填充\0,因此要去掉右侧的\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("张东升") 
  d = mc.decrypt(e) 
  print e,d

看完上述内容,你们掌握怎么在Python中实现AES加密的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注天达云行业资讯频道,感谢各位的阅读!

返回开发技术教程...