python简单实现AES加密和解密

yipeiwu_com5年前Python基础

本文实例为大家分享了python实现AES加密和解密的具体代码,供大家参考,具体内容如下

参考:python实现AES加密和解密

AES加密算法是一种对称加密算法, 他有一个密匙, 即用来加密, 也用来解密

import base64
from Crypto.Cipher import AES
# 密钥(key), 密斯偏移量(iv) CBC模式加密
 
def AES_Encrypt(key, data):
  vi = '0102030405060708'
  pad = lambda s: s + (16 - len(s)%16) * chr(16 - len(s)%16)
  data = pad(data)
  # 字符串补位
  cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
  encryptedbytes = cipher.encrypt(data.encode('utf8'))
  # 加密后得到的是bytes类型的数据
  encodestrs = base64.b64encode(encryptedbytes)
  # 使用Base64进行编码,返回byte字符串
  enctext = encodestrs.decode('utf8')
  # 对byte字符串按utf-8进行解码
  return enctext
 
 
def AES_Decrypt(key, data):
  vi = '0102030405060708'
  data = data.encode('utf8')
  encodebytes = base64.decodebytes(data)
  # 将加密数据转换位bytes类型数据
  cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
  text_decrypted = cipher.decrypt(encodebytes)
  unpad = lambda s: s[0:-s[-1]]
  text_decrypted = unpad(text_decrypted)
  # 去补位
  text_decrypted = text_decrypted.decode('utf8')
  return text_decrypted
 
 
key = '0CoJUm6Qyw8W8jud'
data = 'sdadsdsdsfd'
AES_Encrypt(key, data)
enctext = AES_Encrypt(key, data)
print(enctext)
text_decrypted = AES_Decrypt(key, enctext)
print(text_decrypted) 
hBXLrMkpkBpDFsf9xSRGQQ==
sdadsdsdsfd

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python Gluon参数和模块命名操作教程

本文实例讲述了Python Gluon参数和模块命名操作。分享给大家供大家参考,具体如下: Gluon参数和模块命名教程 在gluon里,每个参数和块都有一个名字(和前缀)。参数名可以由...

python 字典(dict)遍历的四种方法性能测试报告

python中,遍历dict的方法有四种。但这四种遍历的性能如何呢?我做了如下的测试 l = [(x,x) for x in xrange(10000)] d = dict(l)...

Python实现通过解析域名获取ip地址的方法分析

Python实现通过解析域名获取ip地址的方法分析

本文实例讲述了Python实现通过解析域名获取ip地址的方法。分享给大家供大家参考,具体如下: 从网上查找的一些资料,特此做个笔记 案例1: def getIP(domain):...

Python中 CSV格式清洗与转换的实例代码

题目: CSV格式清洗与转换 描述 附件是一个CSV格式文件,提取数据进行如下格式转换:‪‬‪‬‪‬‪...

python 中split 和 strip的实例详解

 python 中split 和 strip的实例详解 一直以来都分不清楚strip和split的功能,实际上strip是删除的意思;而split则是分割的意思。 python...