美文网首页
AES加解密

AES加解密

作者: forjie | 来源:发表于2019-11-13 18:57 被阅读0次

AES是最近比较流行的高级加密算法,是一种对称加密算法

在AES中有很多模式,ECB、CBC等等,这些可以自己找一些文件看看
一般情况下不建议用ECB模式,CBC用的比较多

直接上代码

import json

from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import urlsafe_b64encode,urlsafe_b64decode


class AESCBC(object):
    def __init__(self,key):
        # 有些版本不需要encode,有些版本要
        self.key = key.encode('utf-8')
        # 初始向量
        self.iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0".encode('utf-8')

    def _pad(self,text):
        # 这里是根据填充算法填充字节,我们这里是按照PKCS5padding
        # 打个比方,我们这里的block_size是16,那么最后如果text的字节数没有达到16      
        # 整数,那么就会进行填充,
        # 填充的字节就是pad * pad_size,这里注意,如果刚好被16整除,那么还的添加16个字节
        block_size = AES.block_size
        pad_size = block_size - len(text) % block_size
        if pad_size == 0:
            pad_size = block_size
        pad = chr(pad_size)
        return text + pad * pad_size

    def _unpad(self,dec):
        # 和上面填充字节相反,在解密的时候,删除填充的字节
        return dec[:-ord(dec[len(dec) - 1:])]

    def encrypt(self,text):
        # 有些版本text可以不同json
        json_text = json.dumps(text) 
        content=self._pad(json_text)
        content=content.encode('utf-8')
        cipher = AES.new(self.key,AES.MODE_CBC,self.iv)
        entryptor_str = urlsafe_b64encode(cipher.encrypt(content))
        return entryptor_str.decode('utf-8')

    def decrypt(self,enc):
        enc=urlsafe_b64decode(enc)
        cipher=AES.new(self.key,AES.MODE_CBC,self.iv)
        dec=cipher.decrypt(enc)
        dec=self._unpad(dec)
        return dec.decode('utf-8')

if __name__ == '__main__':
    key = "8ymWLWJzYA1MvLF8"
    text = {'name':1111}
    aes=AESCBC(key)
    encrypt_text=aes.encrypt(text)
    decrypt_text=aes.decrypt(enc)

相关文章

网友评论

      本文标题:AES加解密

      本文链接:https://www.haomeiwen.com/subject/vrskictx.html