8257769: Cipher.getParameters() throws NPE for ChaCha20-Poly1305

Reviewed-by: mullan, valeriep
This commit is contained in:
Jamil Nimeh 2020-12-08 06:10:10 +00:00
parent 6ff18e38b4
commit 500ab45770
2 changed files with 125 additions and 6 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -207,7 +207,7 @@ abstract class ChaCha20Cipher extends CipherSpi {
*/
@Override
protected byte[] engineGetIV() {
return nonce.clone();
return (nonce != null) ? nonce.clone() : null;
}
/**
@ -226,11 +226,16 @@ abstract class ChaCha20Cipher extends CipherSpi {
protected AlgorithmParameters engineGetParameters() {
AlgorithmParameters params = null;
if (mode == MODE_AEAD) {
// In a pre-initialized state or any state without a nonce value
// this call should cause a random nonce to be generated, but
// not attached to the object.
byte[] nonceData = (initialized || nonce != null) ? nonce :
createRandomNonce(null);
try {
// Place the 12-byte nonce into a DER-encoded OCTET_STRING
params = AlgorithmParameters.getInstance("ChaCha20-Poly1305");
params.init((new DerValue(
DerValue.tag_OctetString, nonce).toByteArray()));
DerValue.tag_OctetString, nonceData).toByteArray()));
} catch (NoSuchAlgorithmException | IOException exc) {
throw new RuntimeException(exc);
}
@ -504,7 +509,7 @@ abstract class ChaCha20Cipher extends CipherSpi {
*
* @return a 12-byte array containing the random nonce.
*/
private byte[] createRandomNonce(SecureRandom random) {
private static byte[] createRandomNonce(SecureRandom random) {
byte[] newNonce = new byte[12];
SecureRandom rand = (random != null) ? random : new SecureRandom();
rand.nextBytes(newNonce);