python AES加密解密


AES,是美国联邦政府采用的一种加密技术,AES有几个模式,其中CBC模式是公认的安全性最好的模式,被TLS所采用。

加密与解密双方需确定好key,key的长度可以是16位,24位,32位中的一个,分别对应了不同的算法。

如果key的长度是是16位的,那么被加密的明文长度必须是16的整数倍,但实际使用中,这么巧的事情很难发生,因此就需要对明文进行填充,最常用 的方式就是填充\0,等到解密的时候,再把解密出来的明文右侧的\0全部去掉。你也许会关心,如果我明文最右侧原本就是一堆的\0,那么这么搞,岂不是要 出问题么,是滴,确实会出问题,但这样的明文用来做什么呢?你想多了,这样的明文你这辈子恐怕都不会遇到。

 

AES算法详解:高级加密标准,它是一种对称加密算法,AES只有一个密钥,这个密钥既用来加密,也用于解密。

AES加密方式有五种ECB, CBC, CTR, CFB, OFB。
从安全性角度推荐CBC加密方法,本文介绍了CBC,ECB两种加密方法的python实现。

CBC加密需要一个十六位的key(密钥)和一个十六位iv(偏移量)
ECB加密不需要iv

接收到的数据中只有密钥而没有偏移量。故使用ECB处理密文。

环境准备

python 在 Windows下使用AES时要安装的是pycryptodome(或pycryptodomex) 模块
python 在 Linux下使用AES时要安装的是pycrypto模块

 

# linux环境
import base64
from Crypto.Cipher import AES
from Crypto import Random
import os
import base64
import json
# windows环境
import base64
from Cryptodome.Cipher import AES
import os
import base64
import json
from Cryptodome.Cipher import AES
import base64

class AEScoder():
    def __init__(self):
        self.__encryptKey = "iEpSxImA0vpMUAabsjJWug=="

    # AES加密
    def encrypt(self, content):
        sec_key = AES.new(self.__encryptKey.encode('utf-8'), AES.MODE_ECB)
        encrData = sec_key.encrypt(self.pad_to_16(content))
        return encrData

    # AES解密
    def decrypt(self, content):
        base64_decrypt = base64.decodebytes(content)
        return sec_key.decrypt(base64_decrypt).strip(b"\x00")

    def pad_to_16(self, value):
        while len(value) % 16 != 0:
            value += b"\x00"
        return value

# 注意:需要安装,两个包:
#pip install Ctypto     #windows和linux用的这个包不一样
#pip install binascii




#coding: utf8  
import sys  
from Crypto.Cipher import AES  
from binascii import b2a_hex, a2b_hex  
   
class prpcrypt():  
    def __init__(self, key, iv):  
        self.key = key          self.iv = iv
        self.mode = AES.MODE_CBC  
       
    #加密函数,如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数  
    def encrypt(self, text):  
        cryptor = AES.new(self.key, self.mode, self.iv)  
        #这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用  
        length = 16  
        count = len(text)  
       if(count % length != 0) :  
            add = length - (count % length)  
       else:  
            add = 0  
       text = text + ('\0' * add)  
        self.ciphertext = cryptor.encrypt(text)  
       #因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题  
       #所以这里统一把加密后的字符串转化为16进制字符串 ,当然也可以转换为base64加密的内容,可以使用b2a_base64(self.ciphertext)
       return b2a_hex(self.ciphertext)  
       
    #解密后,去掉补足的空格用strip() 去掉  
    def decrypt(self, text):  
        cryptor = AES.new(self.key, self.mode, self.iv)  
        plain_text = cryptor.decrypt(a2b_hex(text))  
        return plain_text.rstrip('\0')  
   
if __name__ == '__main__':  
    pc = prpcrypt('keyskeyskeyskeys')      #初始化密钥  
    e = pc.encrypt("0123456789ABCDEF")  
    d = pc.decrypt(e)                       
    print e, d  
    e = pc.encrypt("00000000000000000000000000")  
    d = pc.decrypt(e)                    
    print e, d

运行结果如下:

367b61b333c242a4253cfacfe6ea709f         0123456789ABCDEF
2c1969f213c703ebedc36f9e7e5a2b88922ac938c983201c200da51073d00b2c        00000000000000000000000000

class AesEncry(object):
    key = "wwwwwwwwwwwwwwww"  # aes秘钥
 
    def encrypt(self, data):
        data = json.dumps(data)
        mode = AES.MODE_ECB
        padding = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
        cryptos = AES.new(self.key, mode)
        cipher_text = cryptos.encrypt(padding(data).encode("utf-8"))
        return base64.b64encode(cipher_text).decode("utf-8")
 
    def decrypt(self, data):
        cryptos = AES.new(self.key, AES.MODE_ECB)
        decrpytBytes = base64.b64decode(data)
        meg = cryptos.decrypt(decrpytBytes).decode('utf-8')
        return meg[:-ord(meg[-1])]
from Crypto.Cipher import AES
import base64
 
class AEScoder():
    def __init__(self):
        self.__encryptKey = "iEpSxImA0vpMUAabsjJWug=="
        self.__key = base64.b64decode(self.__encryptKey)
    # AES加密
    def encrypt(self,data):
        BS = 16
        pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
        cipher = AES.new(self.__key, AES.MODE_ECB)
        encrData = cipher.encrypt(pad(data))
        #encrData = base64.b64encode(encrData)
        return encrData
    # AES解密
    def decrypt(self,encrData):
        #encrData = base64.b64decode(encrData)
        #unpad = lambda s: s[0:-s[len(s)-1]]
        unpad = lambda s: s[0:-s[-1]]
        cipher = AES.new(self.__key, AES.MODE_ECB)
        decrData = unpad(cipher.decrypt(encrData))
        return decrData.decode('utf-8')

参考:

python 利用Crypto进行AES解密&加密文件 - 简书

python 加密解密 - jihite - 博客园

 使用Python进行AES加密和解密 - 致橡树的你 - 博客园

用Python实现AES加密和解密_guangmingsky的专栏-CSDN博客

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值