Java AES / GCM解密失败

时间:2018-03-29 10:28:13

标签: java encryption aes encryption-symmetric aes-gcm

我正在尝试使用GCM模式进行加密和解密。不幸的是,解密不起作用。

我是否必须为加密和解密类使用相同的初始化向量?我已经尝试过,但没有成功...

keyGen.init(128, random)中的随机参数可能是问题吗?

加密代码:

public class AES128SymmetricEncryption {

    private static final int GCM_NONCE_LENGTH = 12; // in bytes
    private static final int GCM_TAG_LENGTH = 16; // in bytes

    public static void encode (FileInputStream ciphertextSource, FileOutputStream plaintextDestination)
    {
        try {
            int numRead;
            SecureRandom random = SecureRandom.getInstanceStrong();
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            keyGen.init(128, random);
            SecretKey key = keyGen.generateKey();
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
            GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, getIV(random));
            cipher.init(Cipher.ENCRYPT_MODE, key, spec);
            byte[] buf = new byte[2048];

            while ((numRead = ciphertextSource.read(buf)) > 0) {
                byte[] decryptedBlock = cipher.update(buf, 0, numRead);
                plaintextDestination.write(decryptedBlock);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (plaintextDestination != null) {
                    ciphertextSource.close();
                }
                if (plaintextDestination != null) {
                    plaintextDestination.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static byte[] getIV(SecureRandom random) {

        final byte[] nonce = new byte[GCM_NONCE_LENGTH];
        random.nextBytes(nonce);
        System.out.println(nonce);
        return nonce;
    }

    public static void main(String[] args) throws GeneralSecurityException, IOException
    {
        Security.addProvider(new BouncyCastleProvider());

            FileInputStream fis = new FileInputStream("C:/Users/roehrlef/Desktop/Test Data/Source Data/100KB.jpg");
            FileOutputStream fos = new FileOutputStream("C:/Users/roehrlef/Desktop/Test Data/Encrypted Data/encrypted.jpg");
            encode(fis, fos);
    }
}

解密代码:

public class AES128SymmetricDecryption {

    private static final int GCM_NONCE_LENGTH = 12; // in bytes
    private static final int GCM_TAG_LENGTH = 16; // in bytes

    public static void decode (FileInputStream ciphertextSource, FileOutputStream plaintextDestination)
    {
        try {
            int numRead = 0;
            SecureRandom random = SecureRandom.getInstanceStrong();
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            keyGen.init(128, random);
            SecretKey key = keyGen.generateKey();
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
            GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, getIV(random));
            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            CipherInputStream cis = new CipherInputStream(ciphertextSource, cipher);
            byte[] buf = new byte[2048];

            while ((numRead = cis.read(buf)) > 0) {
                byte[] decryptedBlock = cipher.update(buf, 0, numRead);
                plaintextDestination.write(decryptedBlock);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (plaintextDestination != null) {
                    ciphertextSource.close();
                }
                if (plaintextDestination != null) {
                    plaintextDestination.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static byte[] getIV(SecureRandom random) {

        final byte[] nonce = new byte[GCM_NONCE_LENGTH];
        random.nextBytes(nonce);
        System.out.println(nonce);
        return nonce;
    }

    public static void main(String[] args) throws GeneralSecurityException, IOException
    {
        Security.addProvider(new BouncyCastleProvider());

        FileInputStream fis = new FileInputStream("C:/Users/roehrlef/Desktop/Test Data/Encrypted Data/encrypted.jpg");
        FileOutputStream fos = new FileOutputStream("C:/Users/roehrlef/Desktop/Test Data/Decrypted Data/decrypted.jpg");
        decode(fis, fos);
    }
}

1 个答案:

答案 0 :(得分:1)

您使用KeyGenerator两次;一次用于加密,一次用于解密。该类生成一个新的随机密钥。对于对称密码,您需要使用相同的密钥进行加密和解密(因此名称)。

通常,您应将以下类用于以下目的:

对于对称密钥(例如AES,HMAC):

  • KeyGenerator:全新的秘密(对称)密钥;
  • SecretKeyFactory:解码秘密(对称)密钥,例如由大多数密钥类实现的Key#getEncoded()方法生成;

对于非对称公钥/私钥对(例如RSA):

  • KeyPairGenerator:全新的公共/私人非对称密钥对;
  • KeyFactory:从存储的密钥格式解码公钥/私钥(非对称)密钥,例如由大多数密钥类实现的方法Key#getEncoded()生成;

对称和非对称密钥都可以存储在密钥库中:

  • KeyStore:将密钥/证书存储在密钥容器中,例如PKCS#12密钥库;

最后还有其他一些创建键的选项:

  • KeyAgreement:通过密钥协商功能建立密钥,例如Diffie-Hellman密钥交换;
  • Cipher#unwrap:使用Cipher#wrap(或其他平台上的类似功能)使用其他密钥解包(解密)密钥。

您应该在KeyStore中存储和检索密钥 - 您可以将其加载/保存到文件中。请注意,并非所有密钥库都是相同的; Java 9扩展了PKCS#12密钥库的功能,并使其成为默认值。您的代码也会对密钥进行编码,并使用SecretKeyFactory对其进行解码。

或者您可以欺骗并重复使用您在加密期间生成的SecretKey实例,并在以后实施密钥存储。这对于测试目的是有益的。最后,您需要共享对称加密的密钥。

是的,IV必须在双方都是相同的。通常它只存储在密文的前面。对于每次加密,IV应该是唯一的,因此您必须在那里使用随机数生成器。