python3.6执行AES加密及解密方法

python版本:3.6.5 

首先安装pycryptodome

# pip install pycryptodome

加密方式特别简单,代码如下:

方式一:补0

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
 补0方式(ECB加密)
"""

import base64

from Crypto.Cipher import AES


# 补足字符串长度为16的倍数
def add_to_16(s):
    while len(s) % 16 != 0:
        s += '\0'
    return str.encode(s)  # 返回bytes


key = '1234567890123456'  # 密钥长度必须为16、24或32位,分别对应AES-128、AES-192和AES-256
text = 'abcdefg'  # 待加密文本

aes = AES.new(str.encode(key), AES.MODE_ECB)  # 初始化加密器,本例采用ECB加密模式
encrypted_text = str(base64.encodebytes(aes.encrypt(add_to_16(text))), encoding='utf8').replace('\n', '')  # 加密
decrypted_text = str(aes.decrypt(base64.decodebytes(bytes(encrypted_text, encoding='utf8'))).rstrip(b'\0').decode("utf8"))  # 解密

print('加密值:', encrypted_text)
print('解密值:', decrypted_text)

结果为:

方式二:pkcs5

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
 pkcs5补码方式(ECB加密)
"""

import base64

from Crypto.Cipher import AES


# 补足字符串长度为16的倍数
def add_to_16(s):
    while len(s) % 16 != 0:
        s += (16 - len(s) % 16) * chr(16 - len(s) % 16)
    return str.encode(s)  # 返回bytes


key = '1234567890123456'  # 密钥长度必须为16、24或32位,分别对应AES-128、AES-192和AES-256
text = 'abcdefg'  # 待加密文本

aes = AES.new(str.encode(key), AES.MODE_ECB)  # 初始化加密器,本例采用ECB加密模式
encrypted_text = str(base64.encodebytes(aes.encrypt(add_to_16(text))), encoding='utf8').replace('\n', '')  # 加密
decrypted_text = aes.decrypt(base64.decodebytes(bytes(encrypted_text, encoding='utf8'))).decode("utf8")  # 解密
decrypted_text = decrypted_text[:-ord(decrypted_text[-1])]  # 去除多余补位

print('pkcs5加密值:', encrypted_text)
print('pkcs5解密值:', decrypted_text)

结果为:

两种方式加密后的值是不一样的,解密方式也是不一样的。

  • 12
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值