0x01 概述

AES的全称是Advanced Encryption Standard,意思是高级加密标准。本文主要是练习Python实现AES加解密,没有技术含量,大牛请绕行。

0x02 实现

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date: 2020/4/26
# Created by 独自等待
# Blog: https://www.waitalone.cn/
import base64

try:
    from Crypto.Cipher import AES
    from Crypto.Util.Padding import pad, unpad
except ImportError:
    print('请安装加解密库pycryptodome')


class AesSample(object):
    def __init__(self):
        self.key = '315ccddc9e04407abf5c3f87c67f506e'.encode('utf-8')
        self.iv = 'www.waitalone.cn'.encode('utf-8')
        self.mode = AES.MODE_CBC

    def encode(self, data):
        cipher = AES.new(self.key, self.mode, self.iv)
        pad_pkcs7 = pad(data.encode('utf-8'), AES.block_size, style='pkcs7')
        result = base64.encodebytes(cipher.encrypt(pad_pkcs7))
        encrypted_text = str(result, encoding='utf-8').replace('\n', '')
        return encrypted_text

    def decode(self, data):
        cipher = AES.new(self.key, self.mode, self.iv)
        base64_decrypted = base64.decodebytes(data.encode('utf-8'))
        una_pkcs7 = unpad(cipher.decrypt(base64_decrypted), AES.block_size, style='pkcs7')
        decrypted_text = str(una_pkcs7, encoding='utf-8')
        return decrypted_text

    def test(self):
        data1 = 'hello world!'
        data2 = 's/EdN6CpezFrbCmqDi2VY83KqoU9C/UTVxH1+OBAu6U='
        print('加密结果:', self.encode(data1))
        print('解密结果:', self.decode(data2))


if __name__ == '__main__':
    blog = AesSample()
    blog.test()

密码学基础:AES加密算法


版权声明:本文为原创文章,版权归独自等待所有,转载请注明出处!

本文链接:https://www.waitalone.cn/technology/pythonaes.html

友情提示:如果博客部分链接出现404,请留言或者联系博主修复。
Last modification:April 26th, 2020 at 05:25 pm
如果觉得我的文章对你有用,请随意赞赏