天天看點

Python AES使用

#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