怎么在Python中实现AES加密

发布时间:2021-04-30 15:59:52 作者:Leah
来源:亿速云 阅读:157

怎么在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加密的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. aes加密
  2. Python如何实现aes加密解密

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python aes

上一篇:使用python怎么为QT程序添加图标

下一篇:怎么在python中利用matplotlib动态绘制图片

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》