Problem with M2Crypto's AES

情到浓时终转凉″ 提交于 2019-12-02 04:14:26

After correcting the indentation and a small change in __main__, your code seems to work with Python 2.7.3 and M2Crypto-0.21.1:

__author__="gaurav"
__date__ ="$15 Feb, 2011 5:10:59 PM$"
import M2Crypto
from base64 import b64encode, b64decode
ENC=1
DEC=0
def AES_build_cipher(key, iv, op=ENC):
   """"""""
   return M2Crypto.EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=op)

def AES_encryptor(key,msg, iv=None):
   """"""
   #Decode the key and iv
   key = b64decode(key)
   if iv is None:
       iv = '\0' * 16
   else:
       iv = b64decode(iv)

  # Return the encryption function
   def encrypt(data):
       cipher = AES_build_cipher(key, iv, ENC)
       v = cipher.update(data)
       v = v + cipher.final()
       del cipher
       v = b64encode(v)
       return v
   print "AES encryption successful\n"
   return encrypt(msg)

def AES_decryptor(key,msg, iv=None):
   """"""
   #Decode the key and iv
   key = b64decode(key)
   if iv is None:
       iv = '\0' * 16
   else:
       iv = b64decode(iv)

  # Return the decryption function
   def decrypt(data):
       data = b64decode(data)
       cipher = AES_build_cipher(key, iv, DEC)
       v = cipher.update(data)
       v = v + cipher.final()
       del cipher
       return v
   print "AES decryption successful\n"
   return decrypt(msg)

if __name__ == "__main__":
   key="123452345"
   msg="qwrtttrtyutyyyyy"
   encrypted_msg=AES_encryptor(b64encode(key),b64encode(msg))
   print b64decode(AES_decryptor(b64encode(key),encrypted_msg))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!