Problem with M2Crypto's AES

后端 未结 1 572
执笔经年
执笔经年 2021-01-25 02:35

Can someone please point out mistakes in this code:

        __author__=\"gaurav\"
        __date__ =\"$15 Feb, 2011 5:10:59 PM$\"
        import M2Crypto
                


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-25 03:02

    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))
    

    0 讨论(0)
提交回复
热议问题