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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章