求大佬看下这段python加密怎么用js怎么写

import hashlib

from Crypto.Cipher import AES

from Crypto import Random

import base64

密钥

key = “8888888888”

对字符串进行Sha-256加密

def sha256(s):

return hashlib.sha256(s.encode()).hexdigest()[0:32]

用随机偏移量对字符串进行aes CBC PKCS5Padding 加密

def aes_encrypt(text):

secret_key = sha256(key)

print(“secret_key===”,secret_key)

pad = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16)

text = pad(text) # 字符串补位

print(“text===”,text.encode())

iv = Random.new().read(AES.block_size)

print(“iv===”,iv)

cipher = AES.new(bytes.fromhex(secret_key), AES.MODE_CBC, iv)

encrypted_str = cipher.encrypt(text.encode()).hex()

print(“encrypted_str===”,encrypted_str)

str = iv.hex() + encrypted_str

print(base64.b64encode(bytes.fromhex(str), altchars=b’-_’).decode())

if name == ‘main‘:

aes_encrypt(‘{“name”:”46566654”}’)

JS
讨论数量: 2

AES/CBC/PKCS7PADDING 加密,加密后的hex放在iv的hex之后组合成新的字符,新的字符再解析为字节,字节用base64编码获得最后的加密数据

11个月前 评论
npm install crypto-js
npm install crypto


const crypto = require('crypto');
const CryptoJS = require('crypto-js');

const key = '8888888888';

// 使用SHA-256进行哈希
function sha256(s) {
    const hash = crypto.createHash('sha256');
    hash.update(s);
    return hash.digest('hex').substring(0, 32);
}

// AES-CBC PKCS5Padding 加密
function aesEncrypt(text) {
    const secretKey = sha256(key);
    console.log("secret_key ===", secretKey);

    const blockSize = 16;
    const pad = blockSize - text.length % blockSize;
    text = text + String.fromCharCode(pad).repeat(pad);  // PKCS5Padding 填充

    console.log("text ===", Buffer.from(text, 'utf8'));

    const iv = crypto.randomBytes(blockSize); // 生成随机偏移量

    console.log("iv ===", iv);

    const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(secretKey, 'hex'), iv);
    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');

    console.log("encrypted_str ===", encrypted);

    const str = iv.toString('hex') + encrypted;

    // 将加密后的字符串编码为 base64 格式
    const result = Buffer.from(str, 'hex').toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
    console.log(result);

    return result;
}

aesEncrypt('{"name":"46566654"}');

不知道对不对。

9个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!