例子,python m2crypt模块进行AES加密。
专题教程:
AES加密解密算法与实现代码
python aes加密解密算法与模块用法教程
代码:
复制代码 代码示例:
#!/usr/bin/env python
#
# -*- encoding: utf-8 -*-
from M2Crypto.EVP import Cipher
from M2Crypto import m2
iv = ' ' * 16 #任意设置
passKey = "1234567812345678"
text = "defabcdeabcdef1231231231231231adfasdfsdfasdfasdfadfasdfasdfasdfasdfasdf"
def encrypt(buf):
#ecb 模式不受iv影响
cipher = Cipher(alg='aes_128_ecb', key=passKey, iv=iv, op=1) # 1 is encrypt
# padding 有时设置为1
cipher.set_padding(padding=m2.no_padding)
v = cipher.update(buf)
v = v + cipher.final()
del cipher #需要删除
out = ""
for i in v:
out += "%02X" % (ord(i))
print out
return v
def decrypt(buf):
cipher = Cipher(alg='aes_128_ecb', key=passKey, iv=iv, op=0) # 0 is decrypt
cipher.set_padding(padding=m2.no_padding)
v = cipher.update(buf)
v = v + cipher.final()
del cipher #需要删除
print v
return v
decrypt(encrypt(text))
说明:
有时加解密其它语言生成的数据,需要给加密的buf补零到16字节,并将padding设置为False。