nodejs AES加解密和python3 AES加解密

nodejs AES加密
var crypto = require('crypto');

encrypt = function (key, raw) {
    var iv = crypto.randomBytes(16);
    key = new Buffer(key)

    var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);

    var crypted = cipher.update(raw, 'utf8', 'binary');
    crypted += cipher.final('binary');
    crypted = new Buffer(crypted, 'binary')
    
    // 拼接iv串
    enc = Buffer.concat([iv, new Buffer(crypted, 'base64')])
    enc = enc.toString('base64')

    return enc
}

decrypt = function (key, raw) {
  raw = new Buffer(raw, 'base64')

  var iv = raw.slice(0, 16)
  var raw = raw.slice(16, raw.length)
  var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);

  var decoded = decipher.update(raw, 'binary', 'utf8');
  decoded += decipher.final('utf8');

  return decoded;
}

encrypt_dict = function (key, final) {
    return encrypt(key, JSON.stringify(final))
}

module.exports = {
    encrypt: encrypt,
    encrypt_dict: encrypt_dict,
}

row = 'test'
AES_ENCRYPT_SECRET = '74459ca3cf85a81df90da95ff6e7a207'

console.log(encrypt(AES_ENCRYPT_SECRET, row))

final = {
    'test': 'test'
}
console.log(encrypt_dict(AES_ENCRYPT_SECRET, final))
python3 解密
#!/usr/bin/env python

import base64
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher(object):
    """
    A classical AES Cipher. Can use any size of data and any size of password thanks to padding.
    Also ensure the coherence and the type of the data with a unicode to byte converter.
    """
    def __init__(self, key):
        self.bs = 32
        if len(key) >= 32:
            self.key = key[:32]
        else:
            self.key = self._pad(key)

    @staticmethod
    def str_to_bytes(data):
        u_type = type(b''.decode('utf8'))
        if isinstance(data, u_type):
            return data.encode('utf8')
        return data

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * AESCipher.str_to_bytes(chr(self.bs - len(s) % self.bs))

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]

    def encrypt(self, raw):
        raw = self._pad(AESCipher.str_to_bytes(raw))
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8')

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

if __name__ == '__main__':
    # print(base64.b64decode('dnQkZGRnbDFwYmI3N3heaA=='))
    cipher = AESCipher('098f6bcd4621d373cade4e832627b4f6')

    cry_str = 'test'

    encrypted = cipher.encrypt(cry_str)

    import urllib.parse
    encrypted = urllib.parse.unquote(encrypted)

    decrypted = cipher.decrypt(encrypted)
    print(encrypted)
    print(decrypted)
import base64, json
import urllib.parse
from time import time
from app.module.AESCipher import AESCipher

class StatCrypt(AESCipher):
    def encrypt_str(self, s):
        # 加密一串字符
        return urllib.parse.quote_plus(self.encrypt(s))

    def decrypt_str(self, encrypted):
        # 解密一串字符
        decrypted = self.decrypt(encrypted)
        return decrypted

    def encrypt_dict(self, final):
        """
        加密字典
        """

        return self.encrypt_str(json.dumps(final))

    def decrypt_dict(self, encrypted):
        """
        解密字典
        """
        encrypted = urllib.parse.unquote(encrypted)
        decrypted = self.decrypt(encrypted)
        return json.loads(decrypted)

if __name__ == '__main__':
    stat_crypt = StatCrypt('95e90e4b966108abf76cd07f25d588f1')
    final = {
        'vid': 5,
        'action': 4
    }
    encrypted = stat_crypt.encrypt_dict(final)

    import urllib.parse
    encrypted = urllib.parse.unquote(encrypted)
    print(encrypted)

    print(stat_crypt.decrypt_str(encrypted))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值