AES 加密解密示例(walker)

AES 簡介

密碼學中的高級加密標準(Advanced Encryption Standard,AES),又稱Rijndael加密法,是美國聯邦政府採用的一種區塊加密標準。
這個標準用來替代原先的DES(Data Encryption Standard),已經被多方分析且廣爲全世界所使用。經過五年的甄選流程,高級加密標準由美國國家標準與技術研究院 (NIST)於2001年11月26日發佈於FIPS PUB 197,並在2002年5月26日成爲有效的標準。2006年,高級加密標準已然成爲對稱密鑰加密中最流行的算法之一。
該算法爲比利時密碼學家Joan Daemen和Vincent Rijmen所設計,結合兩位作者的名字,以Rijdael之名命之,投稿高級加密標準的甄選流程。(Rijdael的發音近於 "Rhine doll"。)

示例(Python3)

  • 第三方包安裝
pip3 install pycryptodome -i https://pypi.doubanio.com/simple/
pip3 install pkcs7 -i https://pypi.doubanio.com/simple/
  • code
# encoding=utf-8
# author: walker
# date: 2019-09-19
# summary: AES 加密解密示例(CBC模式,pkcs7佔位)

import time
import base64
from urllib import parse
from Crypto.Cipher import AES
from pkcs7 import PKCS7Encoder

def encrypt_aes_pkcs7(plaintext, key, iv):
    r""" 加密
    plaintext: 明文
    key: 密鑰
    iv: 偏移量
    """
    encoder = PKCS7Encoder()
    aes = AES.new(key, AES.MODE_CBC, iv)
    padtext = encoder.encode(plaintext)
    cipherbytes = aes.encrypt(padtext.encode('utf8'))
    ciphertext = base64.b64encode(cipherbytes).decode('utf8')
    return ciphertext

def decrypt_aes_pkcs7(ciphertext, key, iv):
    r""" 解密
    plaintext: 密文
    key: 密鑰
    iv: 偏移量
    """
    encoder = PKCS7Encoder()
    aes = AES.new(key, AES.MODE_CBC, iv)
    cipherbytes = base64.b64decode(ciphertext.encode('utf8'))
    padtext = aes.decrypt(cipherbytes).decode('utf8')
    plaintext = encoder.decode(padtext)   
    return plaintext

if __name__ == '__main__':
    key = b'1CF28E8DBB1F36F9DE50C06ADFFD942B'
    iv = key[0:16]
    timestamp = time.time()

    print('timestamp: %f (%s)' % (timestamp, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))))
    plaintext = "%s*%s" % (timestamp, r'Adobe Spark is an online and mobile design app')
    print('plaintext: %s' % plaintext)
    print('key: %s' % key)
    print('iv: %s' % iv)

    assert(plaintext == decrypt_aes_pkcs7(encrypt_aes_pkcs7(plaintext, key, iv), key, iv))
    
    ciphertext = encrypt_aes_pkcs7(plaintext, key, iv)
    print('ciphertext: %s' % ciphertext)

相關鏈接

本文出自 walker snapshot
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章