执行PBKDF2WithHmacSHA256 + AES / GCM / NoPadding抛出的最小示例:javax.crypto.AEADBadTagException:GCM中的mac检查失败

时间:2017-09-02 11:57:10

标签: java encryption bouncycastle

我用Java编写了这个加密和解密的最小例子,使用Bouncy Castle,PBKDF2WithHmacSHA256从密码中导出密钥,使用AES / GCM / NoPadding来加密/验证有效负载:

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import tech.dashman.dashman.crypto.Util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;

public class Scratch {
    public static void main(String[] args) throws Exception {
        Security.insertProviderAt(new BouncyCastleProvider(), 1);

        String password = "password";
        String payload = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in tincidunt metus. Nam nec diam sed velit blandit porta quis et augue. Praesent imperdiet, nulla vel aliquam porta, dui nisi dictum justo, pellentesque elementum purus orci at leo. Duis scelerisque, urna sit amet fringilla interdum, mauris felis sagittis eros, eleifend tincidunt risus nulla ut erat. Aliquam id sapien non neque rutrum lacinia at vitae lorem. Vivamus quis ligula nunc. Aenean facilisis pretium leo, vitae gravida quam ultrices et. Ut venenatis eros in justo semper fermentum. Pellentesque convallis lectus urna, fringilla rhoncus metus faucibus quis. Sed eu rhoncus tortor. Donec lacinia tempor elementum.";

        int keyLength = 256;
        int saltLength = keyLength / 8; // It's bytes, not bits.
        int iterations = 65536;

        byte[] salt = new SecureRandom().generateSeed(saltLength);
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256", "BC");
        SecretKey passwordKey = secretKeyFactory.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, passwordKey);
        byte[] iv = cipher.getIV();
        System.out.println(Arrays.toString(cipher.getIV()));
        byte[] cipherText = cipher.doFinal(payload.getBytes());

        System.out.println(Base64.toBase64String(cipherText));

        keySpec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength);
        secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256", "BC");
        passwordKey = secretKeyFactory.generateSecret(keySpec);

        cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, passwordKey, new IvParameterSpec(iv));
        System.out.println(Arrays.toString(cipher.getIV()));
        byte[] plainText = cipher.doFinal(payload.getBytes());
        System.out.println(new String(plainText));
    }
}

但它没有用。我得到了这个例外:

Exception in thread "main" javax.crypto.AEADBadTagException: mac check in GCM failed
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$AEADGenericBlockCipher.doFinal(Unknown Source)
    at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at tech.dashman.dashman.Scratch.main(Scratch.java:51)

我已验证,以防万一,两个密码上的init向量相同。我还缺少什么?

1 个答案:

答案 0 :(得分:1)

您正在尝试解密明文而不是密文。倒数第二行:

byte[] plainText = cipher.doFinal(payload.getBytes());

应该是:

byte[] plainText = cipher.doFinal(cipherText);