无法使用Java解密AES-256 GCM [英] Cannot decrypt AES-256 GCM with Java

查看:79
本文介绍了无法使用Java解密AES-256 GCM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个节点模块,可以使用AES-256 GCM进行加密和解密。现在,无论节点模块加密什么,我都试图用Java解密,但是我不断收到AEADBadTagException。

I have a node module that can both encrypt and decrypt with AES-256 GCM. Now I am also trying to decrypt with Java whatever the node module encrypts, but I keep getting a AEADBadTagException.

我已经对节点模块进行了自我测试,并可以确认它是否成功。按预期工作。我知道Java假定身份验证标签是消息的最后一部分,因此我确保该标签是节点模块中附加的最后一部分。

I have tested the node module by itself and can confirm that it works as intended. I know that Java assumes the authentication tag is the last part of the message, so I ensured that the tag is the last thing appended in the node module.

现在我正在测试 hello一词。这是从节点加密的消息:
Q10blKuyyYozaRf0RVYW7bave8mT5wrJzSdURQQa3lEqEQtgYM3ss825YpCQ70A7hpq5ECPafAxdLMSIBZCxzGbv / Cj4i6W4JCJXuS107rUy0tAAQVQQA2ZhbrQ0gNV9QA ==

Right now I'm just testing with the word, "hello". This is the encrypted message from node: Q10blKuyyYozaRf0RVYW7bave8mT5wrJzSdURQQa3lEqEQtgYM3ss825YpCQ70A7hpq5ECPafAxdLMSIBZCxzGbv/Cj4i6W4JCJXuS107rUy0tAAQVQQA2ZhbrQ0gNV9QA==

的盐是不是真的之所以被立即使用,是因为我正在尝试简化测试目的

The salt is not really being used right now because I am trying to keep things simple for testing purposes

节点模块:

var crypto = require('crypto');

var encrypt = function(masterkey, plainText) {
    // random initialization vector
    var iv = crypto.randomBytes(12);

    // random salt
    var salt = crypto.randomBytes(64);

    var key = masterkey;

    // AES 256 GCM Mode
    var cipher = crypto.createCipheriv('aes-256-gcm', key, iv);

    // encrypt the given text
    var encrypted = Buffer.concat([cipher.update(plainText, 'utf8'), cipher.final()]);

    // extract the auth tag
    var tag = cipher.getAuthTag();

    return Buffer.concat([salt, iv, encrypted, tag]).toString('base64');
};

var decrypt = function(masterkey, encryptedText) {
    // base64 decoding
    var bData = new Buffer(encryptedText, 'base64');

    // convert data to buffers
    var salt = bData.slice(0, 64);
    var iv = bData.slice(64, 76);
    var tag = bData.slice(bData.length - 16, bData.length);
    var text = bData.slice(76, bData.length - 16);

    var key = masterkey;

    // AES 256 GCM Mode
    var decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
    decipher.setAuthTag(tag);

    // encrypt the given text
    var decrypted = decipher.update(text, 'binary', 'utf8') + decipher.final('utf8');

    return decrypted;
};

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

Java类:
现在主要的方法是进行测试,以后将删除。

Java Class: The main method is just there for testing right now and will be removed later.

package decryption;

import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class DecryptAES256 {

    private static String salt;
    private static byte[] ivBase64;
    private static String base64EncryptedText;
    private static String key;

    public static void main(String[] args) {
        String key = "123456789aabbccddeefffffffffffff";
        String sourceText = "Q10blKuyyYozaRf0RVYW7bave8mT5wrJzSdURQQa3lEqEQtgYM3ss825YpCQ70A7hpq5ECPafAxdLMSIBZCxzGbv/Cj4i6W4JCJXuS107rUy0tAAQVQQA2ZhbrQ0gNV9QA==";
        System.out.println(decrypt(key, sourceText));
    }

    public static String decrypt(String masterkey, String encryptedText) {
        byte[] parts = encryptedText.getBytes();
        salt = new String(Arrays.copyOfRange(parts, 0, 64));
        ivBase64 = Arrays.copyOfRange(parts, 64, 76);
        ivBase64 = Base64.getDecoder().decode(ivBase64);
        base64EncryptedText = new String(Arrays.copyOfRange(parts, 76, parts.length));
        key = masterkey;
        byte[] decipheredText = decodeAES_256_CBC();
        return new String(decipheredText);
    }

    private static byte[] decodeAES_256_CBC() {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            byte[] text = base64EncryptedText.getBytes();
            GCMParameterSpec params = new GCMParameterSpec(128, ivBase64, 0, ivBase64.length);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, params);
            return cipher.doFinal(Base64.getDecoder().decode(text));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to decrypt");
        }
    }
}


推荐答案

抛出异常是正常的,您的Java代码中有两个问题:

The exception thrown is normal, you have 2 problems in your Java code:

1- 您的AES密钥未正确解码 :将其包装为十六进制表示形式,然后将其解码,就好像没有解码一样。调用 SecretKeySpec()时,需要将其从十六进制表示形式转换为字节。

1- your AES key is not decoded correctly: it is wrapped in hexadecimal representation and you decode it as if it was not. You need to convert it from the hexadecimal representation to bytes, when calling SecretKeySpec().

替换以下行:

SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

通过这个:

SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");

请注意,要访问Hex类,您需要导入 org .apache.commons.codec.binary.Hex 放在类文件中,并在项目中包含相应的Apache commons-codec 库。

Note that to get access to the Hex class, you need to import org.apache.commons.codec.binary.Hex in your class file and include the corresponding Apache commons-codec library in your project.

2- 在将其转换为base64之前先拆分了base64密文,这不是正确的处理顺序:

2- you split your base64 cipher text before having converted it to base64, this is not the correct order to do things:

decrypt()方法的开始,您需要首先调用 Base64.getDecoder()。对密文( sourceText )进行解码(),然后将其拆分为相应的字段。

At the start of your decrypt() method, you need to first call Base64.getDecoder().decode() on your cipher text (sourceText) before splitting it into the corresponding fields.

如果要使用Java中使用AES-256-GCM的示例,可以查看我几个月前编写的以下示例: https://github.com/AlexandreFenyo/kif-idp-client

If you want an example of using AES-256-GCM in Java, you can look at the following example I had written some months ago: https://github.com/AlexandreFenyo/kif-idp-client

要加密和加密的源代码解密在以下文件: https:// github.com/AlexandreFenyo/kif-idp-client/blob/master/src/kif/libfc/Tools.java

The source code to encrypt and decrypt is in the following file: https://github.com/AlexandreFenyo/kif-idp-client/blob/master/src/kif/libfc/Tools.java

请参见名为 encodeGCM() decodeGCM()

这些方法是由主类在这里调用: https ://github.com/AlexandreFenyo/kif-idp-client/blob/master/src/kif/libfc/CommandLine.java

Those methods are called by the main class here: https://github.com/AlexandreFenyo/kif-idp-client/blob/master/src/kif/libfc/CommandLine.java

这篇关于无法使用Java解密AES-256 GCM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆