Python/JavaScript 实现AES CBC加密

python(文本中含有中文通用版)

import base64
from Crypto.Cipher import AES


# 需要补位,使用PKCS#7填充方式
def add_to_16(value):
    pad_size = 16 - len(value.encode('utf-8')) % 16
    pad = chr(pad_size) * pad_size
    return (value + pad).encode('utf-8')


# 加密方法
def aes_encrypt(key, t, iv):
    aes = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))  # 初始化加密器
    encrypt_aes = aes.encrypt(add_to_16(t))  # 先进行 aes 加密
    encrypted_text = base64.encodebytes(encrypt_aes).decode('utf-8')  # 执行加密并转码返回字符串
    return encrypted_text


# 解密方法
def aes_decrypt(key, t, iv):
    aes = AES.new(key.encode("utf-8"), AES.MODE_CBC, iv.encode("utf-8"))         # 初始化加密器
    base64_decrypted = base64.decodebytes(t.encode(encoding='utf-8'))  # 优先逆向解密 base64 成 bytes
    decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').strip()  # 执行解密密并转码返回str
    return decrypted_text


if __name__ == '__main__':
    secret_key = '1234567812345678'
    text = "你好"
    # text = "nihao"
    iv = "1234567812345678"           # 初始向量
    encrypt_str = aes_encrypt(secret_key, text, iv)
    print('加密字符串:', encrypt_str)
    decrypted_str = aes_decrypt(secret_key, encrypt_str, iv)
    print('解密字符串:', decrypted_str)

JavaScript

var crypto = require("crypto-js")

function AES_encrypt(e, t) {
    var n = crypto.AES.encrypt(JSON.stringify(e), crypto.enc.Utf8.parse(t.k), {
                        iv: crypto.enc.Utf8.parse(t.i),
                        mode: crypto.mode.CBC,
                        padding: crypto.pad.Pkcs7
                    });
    var data = n.toString()
    console.log(data)
    return data
}

function AES_decrypt(e, t) {
    var n = crypto.AES.decrypt(e, crypto.enc.Utf8.parse(t.k), {
        iv: crypto.enc.Utf8.parse(t.i),
        mode: crypto.mode.CBC,
        padding: crypto.pad.Pkcs7
    });
    return n.toString(crypto.enc.Utf8);
}


var e = {"mid":1000,"platformId":2}
var t = {
    "k": "1234567812345678",
    "i": "1234567812345678"
}
data = AES_encrypt(e, t)
console.log("加密字符串:", data)
result = AES_decrypt(data, t)
console.log("解密字符串:", result)

你可能感兴趣的:(学习笔记,python,JavaScript,python,javascript,AES)