用AES-256-GCM加密的Node.js数据无法用Java解密

问题描述 投票:0回答:0

Node.js加密算法

import crypto from "crypto"
function(data, key) {
    const iv = crypto.randomBytes(12)
    const cipher = crypto.createCipheriv('aes-256-gcm', key, iv)
    let enc = cipher.update(data, 'utf8', 'base64')
    enc += cipher.final('base64')
    return [enc, cipher.getAuthTag().toString('base64'), iv.toString("base64")].join('.')
}

Java解密算法

public static String decrypt(String encryData) throws Exception {
        String[] parts = encryData.split("\\.");
        byte[] encrypted = parts[0].getBytes();
        byte[] tag = parts[1].getBytes();
        byte[] iv = parts[2].getBytes();

        GCMParameterSpec ivSpec = new GCMParameterSpec(128, iv);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES"), ivSpec);
        cipher.update(tag);
        byte[] bytes = cipher.doFinal(encrypted);
        return new String(bytes);
    }

Java 抛出以下异常

线程“main”中的异常 javax.crypto.AEADBadTagException:标签不匹配!

javascript java aes aes-gcm
© www.soinside.com 2019 - 2024. All rights reserved.