前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >AES 加密解密示例(walker)

AES 加密解密示例(walker)

作者头像
py3study
发布2020-01-06 18:35:34
2.1K0
发布2020-01-06 18:35:34
举报
文章被收录于专栏:python3python3

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'walker snapshot')
    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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • AES 简介
  • 示例(Python3)
  • 相关链接
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档