python aes new_python3 aes加解密

本文介绍了如何使用Python的pycryptodome库实现AES(Advanced Encryption Standard)的加密和解密,包括CBC模式操作,展示了如何设置密钥和初始化向量,并提供了一个实例演示了'hello world'字符串的加密和解密过程。
摘要由CSDN通过智能技术生成

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值