吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1338|回复: 18
收起左侧

[求助] aes加解密问题求助

[复制链接]
gggqqqxxx 发表于 2025-7-11 14:56
本帖最后由 gggqqqxxx 于 2025-7-11 15:04 编辑
private static final String [i]ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String [i]AES = "AES";
private static final int [i]IV_LENGTH = 16;

private static final String [i]SECRET_KEY = "我的密匙";
public static String decrypt(String encryptedBase64) {
        try {
            // 解码Base64
            byte[] combined = Base64.getDecoder().decode(encryptedBase64);
            // 提取IV
            byte[] iv = new byte[IV_LENGTH];
            System.arraycopy(combined, 0, iv, 0, iv.length);
            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            // 提取密文
            byte[] encrypted = new byte[combined.length - iv.length];
            System.arraycopy(combined, iv.length, encrypted, 0, encrypted.length);

            // 创建密钥规范
            SecretKeySpec secretKey = new SecretKeySpec(
                    SECRET_KEY.getBytes(StandardCharsets.UTF_8), AES
            );

            // 解密数据
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
            byte[] decrypted = cipher.doFinal(encrypted);

            return new String(decrypted, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new SecurityException("Decryption failed", e);
        }
    }

这是后端解密方法,想把这个方法转换成前端的方法,下边是我转的,不知道为啥一直解密不出来
const SECRET_KEY = "我的密匙"; // 与后端保持一致
const IV_LENGTH = 16; // 16字节 = 128位
function decrypt(encryptedBase64) {
    try {
      // 解码Base64
      const combined = CryptoJS.enc.Base64.parse(encryptedBase64);
      console.log(combined);

      // 提取IV(前16字节)
      const iv = CryptoJS.lib.WordArray.create(
        combined.words.slice(0, IV_LENGTH / 4), 
        IV_LENGTH
      );

      // 提取密文(剩余部分)
      const ciphertext = CryptoJS.lib.WordArray.create(
        combined.words.slice(IV_LENGTH / 4), 
        combined.sigBytes - IV_LENGTH
      );

      // 创建密钥
      const key = CryptoJS.enc.Utf8.parse(SECRET_KEY);

      // 解密数据
      const decrypted = CryptoJS.AES.decrypt(
        { ciphertext: ciphertext },
        key,
        {
          iv: iv,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
        }
      );

      return decrypted.toString(CryptoJS.enc.Utf8);
    } catch (e) {
      throw new Error('Decryption failed: ' + e.message);
    }
}



需要大佬帮我看下前端代码转换的哪里不对吗?

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

414269678 发表于 2025-7-11 15:42
一个PKCS5一个PKCS7吧
 楼主| gggqqqxxx 发表于 2025-7-11 15:51
414269678 发表于 2025-7-11 15:42
一个PKCS5一个PKCS7吧

我搜了,前端的CryptoJS.pad.Pkcs7对应Java的PKCS5Padding
ImpJ 发表于 2025-7-11 16:00
[Python] 纯文本查看 复制代码
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto import Random
import subprocess
import json
import os

SECRET_KEY = "16-bytesecretkey".encode('utf-8')
IV_LENGTH = 16


def encrypt(plaintext):
    iv = Random.new().read(IV_LENGTH)

    cipher = AES.new(SECRET_KEY, AES.MODE_CBC, iv)

    padded_data = pad(plaintext.encode('utf-8'), AES.block_size)
    encrypted = cipher.encrypt(padded_data)

    combined = iv + encrypted

    return base64.b64encode(combined).decode('utf-8')


def test_decryption(encrypted_base64, expected_plaintext):
    test_data = {
        "encrypted": encrypted_base64,
        "expected": expected_plaintext
    }

    with open('test_data.json', 'w', encoding='utf-8') as f:
        json.dump(test_data, f, ensure_ascii=False)

    result = subprocess.run(
        ['node', 'test_decrypt.js'],
        capture_output=True,
        text=True
    )

    if result.returncode == 0:
        print("✅ 测试通过: JS解密成功")
        print(f"原始文本: {expected_plaintext}")
        print(f"解密结果: {result.stdout.strip()}")
    else:
        print("❌ 测试失败: JS解密出错")
        print("错误信息:")
        print(result.stderr)


def main():
    print("🔐 AES解密功能验证工具")
    print("=" * 50)

    test_cases = [
        ("Hello World!", "短文本测试"),
        ("Python验证前端JS解密功能", "中文测试"),
        ("A" * 100, "长文本测试"),
        ("特殊字符测试: !@#$%^&*()_+-=[]{}|;:,.<>?/", "特殊字符")
    ]

    for plaintext, description in test_cases:
        print(f"\n&#128295; 测试用例: {description}")
        print(f"原始文本: {plaintext}")

        encrypted_base64 = encrypt(plaintext)
        print(f"加密结果: {encrypted_base64[:30]}... (Base64)")

        test_decryption(encrypted_base64, plaintext)

    if os.path.exists('test_data.json'):
        os.remove('test_data.json')


if __name__ == "__main__":
    main()

[JavaScript] 纯文本查看 复制代码
const CryptoJS = require("crypto-js");
const fs = require("fs");

const testData = JSON.parse(fs.readFileSync("test_data.json", "utf-8"));
const encryptedBase64 = testData.encrypted;
const expectedPlaintext = testData.expected;

function decrypt(encryptedBase64) {
    const SECRET_KEY = "16-bytesecretkey";
    const IV_LENGTH = 16;

    try {
        const combined = CryptoJS.enc.Base64.parse(encryptedBase64);

        const iv = CryptoJS.lib.WordArray.create(
            combined.words.slice(0, IV_LENGTH / 4),
            IV_LENGTH
        );

        const ciphertext = CryptoJS.lib.WordArray.create(
            combined.words.slice(IV_LENGTH / 4),
            combined.sigBytes - IV_LENGTH
        );

        const key = CryptoJS.enc.Utf8.parse(SECRET_KEY);

        const decrypted = CryptoJS.AES.decrypt(
            { ciphertext: ciphertext },
            key,
            {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            }
        );

        return decrypted.toString(CryptoJS.enc.Utf8);
    } catch (e) {
        console.error("解密失败:", e);
        throw e;
    }
}

try {
    const decryptedText = decrypt(encryptedBase64);

    if (decryptedText === expectedPlaintext) {
        console.log(decryptedText);
        process.exit(0);
    } else {
        console.error("解密结果不匹配");
        console.error("期望:", expectedPlaintext);
        console.error("实际:", decryptedText);
        process.exit(1);
    }
} catch (error) {
    console.error("测试失败:", error);
    process.exit(1);
}

我用python和js还原了一下,可以正常解密,但是如果SECRET_KEY是中文的话会报错。
 楼主| gggqqqxxx 发表于 2025-7-11 16:10
ImpJ 发表于 2025-7-11 16:00
[mw_shl_code=python,true]
import base64
from Crypto.Cipher import AES

复制你的前端代码还是报错呢、
密匙 KkHj3R8vP5tFwD2q
我的密文是这样的
"Dt0/UUEURArl2JhbM5Upui3iOJllNB0iR7Qwz6IeU8/iGF3oznI12jwlVun9vJ26n4p8L5pI8HpqrB3rCWCqmJetKrTOXp7Ns1bj43q3wg/OBWp5ygmd/1/rCSjP27xfvEbgCS0K3kTF27l+TlZpoaTiKekwhBS/PWqWVq+YPJEoIonhvTnsy23H+g1q6WSIV0KUNzeSjws+M/xau88jKJcjsVOBLpzRCskRSkrN538="
ImpJ 发表于 2025-7-11 16:30
gggqqqxxx 发表于 2025-7-11 16:10
复制你的前端代码还是报错呢、
密匙 KkHj3R8vP5tFwD2q
我的密文是这样的

我用你的密钥在我本地试了一下我这好用
 楼主| gggqqqxxx 发表于 2025-7-11 16:37
ImpJ 发表于 2025-7-11 16:30
我用你的密钥在我本地试了一下我这好用

真是奇怪了 弄了半天还是不行
Mr.救赎 发表于 2025-7-11 17:02
不行,把报错的代码发出来 ,大佬帮你分析下什么问题
shanjzhu 发表于 2025-7-11 17:08
为啥IV和密文还要再转一下,直接解密不行吗
shanjzhu 发表于 2025-7-11 17:10
shanjzhu 发表于 2025-7-11 17:08
为啥IV和密文还要再转一下,直接解密不行吗

woc,怎么撤回评论。我是傻逼
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-8-12 18:08

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表