脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python简单实现AES加密和解密

python简单实现AES加密和解密

2021-06-10 00:06Frankssss Python

这篇文章主要为大家详细介绍了python简单实现AES加密和解密,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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)
?
1
2
hBXLrMkpkBpDFsf9xSRGQQ==
sdadsdsdsfd

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/frank-shen/p/10281708.html

延伸 · 阅读

精彩推荐