您的位置:首页 > 编程语言 > Python开发

Python AES使用

2016-01-14 11:41 183 查看
#encoding:utf-8
"""
示例代码
easy_install  install pycrypto‎
pip  install pycrypto‎ 都不行
要源码安装https://www.dlitz.net/software/pycrypto/
修改编译器C:\Python27\Lib\distutils\msvc9compiler.py中270行指定vc编译器
vcvarsall="E:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\vcvarsall.bat"
本人的环境是vs2015
"""
from Crypto.Cipher import AES
from Crypto import Random
import base64

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]

"""
android  java  python通用AES加解密算法 已测试成功

上例中的key是16位, 还可以是24 或 32 位长度, 其对应为 AES-128, AES-196 和 AES-256.
解密则可以用以下代码进行:
"""
if __name__== "__main__":
bkey = "1234567890123456"
print(bkey)
raw="androidtest你好我来自中国";
raw = pad(raw)
iv ="0102030405060708";
print("iv="+iv)
cipher = AES.new(bkey, AES.MODE_CBC, iv )
print(len(raw))
print(raw)

ciphertext= cipher.encrypt(raw)
ciphertext_base64=base64.b64encode(ciphertext)
print(ciphertext_base64)

#保存密文到文件 给Java相互加解密
f = file('d:/aes.txt','w+')
f.write(ciphertext_base64)
f.close()
#读文件
txt_base64=file('d:/aes.txt','r').read()
print(txt_base64)

enc=base64.b64decode(txt_base64)
cipher = AES.new(bkey, AES.MODE_CBC, iv )

text=cipher.decrypt(enc);
print(len(text))
print(text)

print(text.encode("hex"))

plaintext= unpad(text)
print "%s" % plaintext
print("解密java加密的密文");

java_base64=file('d:/aes_java.txt','r').read()
print('java_base64='+java_base64)

#每次都要调用cipher = AES.new(bkey, AES.MODE_CBC, iv )
enc=base64.b64decode(java_base64)
cipher = AES.new(bkey, AES.MODE_CBC, iv )
java_plaintext=cipher.decrypt(enc);
print(len(java_plaintext))
print(java_plaintext.encode("hex"))
plaintext= unpad(java_plaintext)
#怎么编码
print "%s" % plaintext
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: