由于mysql目前的仅支持aes ecb加密方法,不能使用mysql直接处理cbc数据只能用python来搞定了


AES输入的加密字符必须是16的倍数,php的默认补零,所以解密的时候还需要rtrim掉零。python没有自动做这件事情,所以要自己补零。


脚本内容

import sys,binascii
from Crypto.Cipher import AES

#python没有自动补足功能,将不符合16位补充
def length(string):
   padding = '\0'
   length = 16
   count = len(string)
   if count < length:
       add = (length - count)
       string += (padding * add)
   elif count > length:
       add = (length - (count % length))
       string += (padding * add)
   return string


key = 'keyscode'
iv = '1234567890123456'
aes_key = length(key)
aes_iv = length(iv)
data = sys.argv[1]#加密原始数据传递
aes_data = length(data)




###encode string
encobj = AES.new(aes_key, AES.MODE_CBC, aes_iv)
ciphertext1 = encobj.encrypt(aes_data)
aes_code = ciphertext1.encode('hex')


###decode string
ciphertext = binascii.unhexlify(aes_code)
decobj = AES.new(aes_key, AES.MODE_CBC, aes_iv)
aes_dec = decobj.decrypt(ciphertext)


print 'LOWER AES_ENCODE:  ' +  aes_code
print 'UPPER AES_ENCODE:  ' +  aes_code.upper()
print 'UPPER AES_DECODE:  '  + aes_dec



下载:https://pypi.python.org/pypi/pycrypto

参考资料:http://ju.outofmemory.cn/entry/30305

加密算法资料:http://www.baike.com/wiki/AES%E5%8A%A0%E5%AF%86%E7%AE%97%E6%B3%95