AES加密

来源:互联网 发布:2008最伤感网络歌曲 编辑:程序博客网 时间:2024/06/11 03:46
#coding=utf-8  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("秘钥长度不对,请重新检查秘钥长度")          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__': paint_txt=raw_input("请输入明文:");  key=raw_input("请输入秘钥:"); key_len=len(key) if not key_len == 16 and not key_len == 24 and not key_len == 32:      raise Exception("秘钥长度不对,请重新检查秘钥长度")     mc = MyCrypto(key)  e = mc.encrypt(paint_txt)  d = mc.decrypt(e)  print "加密后是:%s ;   解密后是:%s   "%(e ,d)
原创粉丝点击