无法使用Java解密长AES-256 GCM消息

时间:2017-09-19 18:38:56

标签: java node.js aes aes-gcm

与此问题相关: Cannot decrypt AES-256 GCM with Java

如果加密的消息很短,即两个字左右,Java解密问题似乎只能解决。我尝试过“hello”和“short string”这两个词,这两个词都被解密了。当我尝试类似的东西时,

  

包含更多数字的字母数字字符串test1,例如5,4,3,2,1

再次出现了AEADBadTagException。

编辑:

此问题与加密邮件的持续时间直接相关。两个词有点夸张,但只要加密的消息大约只要这个或更长,那么Java就会遇到异常。

加密邮件样本:

  

d + nyOuSfH3wup + 5KHJRQyVwVHE0nn7dOfLQsSxb2LsR1LuogHxmVobHoQSTbdyqupd / UvwGfbhkUQz + 8CjIBSd7FoEVpgpYv9dAQ3GGUr3AtA + rJJrFHo / EM443sQlSOG4cIBQ7trF7udmrIhtiZ9wMchaBEJFmDBL5Jwl8ZMM0ath8VNWqfyyhghPW8U2NiORAy5mw6v07o7v3UT2   lBzJThBsM =

用节点解密:

  

这是一个更长的字符串,使加密的消息比以前更长

编辑2:

Java代码:

package decryption;

import java.io.UnsupportedEncodingException;
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[] iv;
    private static byte[] encryptedMessageAndTag;
    private static byte[] key;

    public static void main(String[] args) {
        String key = "123456789aabbccddeefffffffffffff";
        String sourceText = "zMX8Xp8lCLGP3FsF7dy1uEODFG0+lhpoWR+xZPpNAXm2D39+CJUK5Kk0z4NbDfb/WbP8lHVWcTOuXf8hRA1AmtEV2G5kP3SH3mrGbyf4QthR4aOTqEQQAvt1T8LlIkBlgx32gehP/nwwm3DYyJV+NnN21Ac17L4=";
        System.out.println(decrypt(key, sourceText));
    }

    public static String decrypt(String masterkey, String encryptedText) {
        // decode encryptedText 
        encryptedText = new String(Base64.getDecoder().decode(encryptedText.getBytes()));

        // extract the different parts
        byte[] parts = encryptedText.getBytes();
        salt = new String(Arrays.copyOfRange(parts, 0, 64)); // not using for testing purposes
        iv = Arrays.copyOfRange(parts, 64, 76);
        encryptedMessageAndTag = Arrays.copyOfRange(parts, 76, parts.length);
        try {
            key = masterkey.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            // not going to reach here
        }

        // call helper method to decrypt
        byte[] decipheredText = decodeAES_256_CBC();
        return new String(decipheredText);
    }

    private static byte[] decodeAES_256_CBC() {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            GCMParameterSpec params = new GCMParameterSpec(128, iv, 0, iv.length);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, params);
            return cipher.doFinal(encryptedMessageAndTag);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to decrypt");
        }
    }
}

编辑3:

清理Java代码以提高可读性

0 个答案:

没有答案