8153029: ChaCha20 Cipher Implementation

Add the ChaCha20 and ChaCha20-Poly1305 Cipher implementations

Reviewed-by: mullan
This commit is contained in:
Jamil Nimeh 2018-05-31 07:05:10 -07:00
parent 89251ae9a3
commit fcb805f9a6
10 changed files with 3556 additions and 3 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,213 @@
/*
* Copyright (c) 2018, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.crypto.provider;
import java.io.IOException;
import java.security.AlgorithmParametersSpi;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import javax.crypto.spec.IvParameterSpec;
import sun.security.util.*;
/**
* This class implements the parameter set used with the ChaCha20-Poly1305
* algorithm. The parameter definition comes from
* <a href="https://tools.ietf.org/html/rfc8103"><i>RFC 8103</i></a>
* and is defined according to the following ASN.1:
*
* <pre>
* id-alg-AEADChaCha20Poly1305 OBJECT IDENTIFIER ::=
{ iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1)
pkcs9(9) smime(16) alg(3) 18 }
* AEADChaCha20Poly1305Nonce ::= OCTET STRING (SIZE(12))
* </pre>
*
* The AlgorithmParameters may be instantiated either by its name
* ("ChaCha20-Poly1305") or via its OID (1.2.840.113549.1.9.16.3.18)
*/
public final class ChaCha20Poly1305Parameters extends AlgorithmParametersSpi {
private static final String DEFAULT_FMT = "ASN.1";
private byte[] nonce;
public ChaCha20Poly1305Parameters() {}
/**
* Initialize the ChaCha20Poly1305Parameters using an IvParameterSpec.
*
* @param paramSpec the {@code IvParameterSpec} used to configure
* this object.
*
* @throws InvalidParameterSpecException if an object of a type other
* than {@code IvParameterSpec} is used.
*/
@Override
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException {
if (!(paramSpec instanceof IvParameterSpec)) {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
IvParameterSpec ivps = (IvParameterSpec)paramSpec;
// Obtain the nonce
nonce = ivps.getIV();
if (nonce.length != 12) {
throw new InvalidParameterSpecException("ChaCha20-Poly1305 nonce" +
" must be 12 bytes in length");
}
}
/**
* Initialize the ChaCha20Poly1305Parameters from a DER encoded
* parameter block.
* @param encoded the DER encoding of the nonce as an OCTET STRING.
*
* @throws IOException if the encoded nonce is not 12 bytes long or a DER
* decoding error occurs.
*/
@Override
protected void engineInit(byte[] encoded) throws IOException {
DerValue val = new DerValue(encoded);
// Get the nonce value
nonce = val.getOctetString();
if (nonce.length != 12) {
throw new IOException(
"ChaCha20-Poly1305 nonce must be 12 bytes in length");
}
}
/**
* Initialize the ChaCha20Poly1305Parameters from a DER encoded
* parameter block.
*
* @param encoded the DER encoding of the nonce and initial block counter.
* @param decodingMethod the decoding method. The only currently accepted
* value is "ASN.1"
*
* @throws IOException if the encoded nonce is not 12 bytes long, a DER
* decoding error occurs, or an unsupported decoding method is
* provided.
*/
@Override
protected void engineInit(byte[] encoded, String decodingMethod)
throws IOException {
if (decodingMethod == null ||
decodingMethod.equalsIgnoreCase(DEFAULT_FMT)) {
engineInit(encoded);
} else {
throw new IOException("Unsupported parameter format: " +
decodingMethod);
}
}
/**
* Return an IvParameterSpec with the same parameters as those
* held in this object.
*
* @param paramSpec the class name of the spec. In this case it should
* be {@code IvParameterSpec.class}.
*
* @return a {@code IvParameterSpec} object containing the nonce
* value held in this object.
*
* @throws InvalidParameterSpecException if a class other than
* {@code IvParameterSpec.class} was specified in the paramSpec
* parameter.
*/
@Override
protected <T extends AlgorithmParameterSpec>
T engineGetParameterSpec(Class<T> paramSpec)
throws InvalidParameterSpecException {
if (IvParameterSpec.class.isAssignableFrom(paramSpec)) {
return paramSpec.cast(new IvParameterSpec(nonce));
} else {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
}
/**
* Return the encoded parameters in ASN.1 form.
*
* @return a byte array containing the DER-encoding for the
* ChaCha20-Poly1305 parameters. This will be the nonce
* encoded as a DER OCTET STRING.
*
* @throws IOException if any DER encoding error occurs.
*/
@Override
protected byte[] engineGetEncoded() throws IOException {
DerOutputStream out = new DerOutputStream();
out.write(DerValue.tag_OctetString, nonce);
return out.toByteArray();
}
/**
* Return the encoded parameters in ASN.1 form.
*
* @param encodingMethod the encoding method to be used. This parameter
* must be "ASN.1" as it is the only currently supported encoding
* format. If the parameter is {@code null} then the default
* encoding format will be used.
*
* @return a byte array containing the DER-encoding for the
* ChaCha20-Poly1305 parameters.
*
* @throws IOException if any DER encoding error occurs or an unsupported
* encoding method is provided.
*/
@Override
protected byte[] engineGetEncoded(String encodingMethod)
throws IOException {
if (encodingMethod == null ||
encodingMethod.equalsIgnoreCase(DEFAULT_FMT)) {
return engineGetEncoded();
} else {
throw new IOException("Unsupported encoding format: " +
encodingMethod);
}
}
/**
* Creates a formatted string describing the parameters.
*
* @return a string representation of the ChaCha20 parameters.
*/
@Override
protected String engineToString() {
String LINE_SEP = System.lineSeparator();
HexDumpEncoder encoder = new HexDumpEncoder();
StringBuilder sb = new StringBuilder(LINE_SEP + "nonce:" +
LINE_SEP + "[" + encoder.encodeBuffer(nonce) + "]");
return sb.toString();
}
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2018, 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
@ -111,16 +111,20 @@ final class KeyGeneratorCore {
protected HmacSHA2KG(String algoName, int len) {
core = new KeyGeneratorCore(algoName, len);
}
@Override
protected void engineInit(SecureRandom random) {
core.implInit(random);
}
@Override
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
core.implInit(params, random);
}
@Override
protected void engineInit(int keySize, SecureRandom random) {
core.implInit(keySize, random);
}
@Override
protected SecretKey engineGenerateKey() {
return core.implGenerateKey();
}
@ -153,13 +157,16 @@ final class KeyGeneratorCore {
public RC2KeyGenerator() {
core = new KeyGeneratorCore("RC2", 128);
}
@Override
protected void engineInit(SecureRandom random) {
core.implInit(random);
}
@Override
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
core.implInit(params, random);
}
@Override
protected void engineInit(int keySize, SecureRandom random) {
if ((keySize < 40) || (keySize > 1024)) {
throw new InvalidParameterException("Key length for RC2"
@ -167,6 +174,7 @@ final class KeyGeneratorCore {
}
core.implInit(keySize, random);
}
@Override
protected SecretKey engineGenerateKey() {
return core.implGenerateKey();
}
@ -178,13 +186,16 @@ final class KeyGeneratorCore {
public ARCFOURKeyGenerator() {
core = new KeyGeneratorCore("ARCFOUR", 128);
}
@Override
protected void engineInit(SecureRandom random) {
core.implInit(random);
}
@Override
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
core.implInit(params, random);
}
@Override
protected void engineInit(int keySize, SecureRandom random) {
if ((keySize < 40) || (keySize > 1024)) {
throw new InvalidParameterException("Key length for ARCFOUR"
@ -192,9 +203,38 @@ final class KeyGeneratorCore {
}
core.implInit(keySize, random);
}
@Override
protected SecretKey engineGenerateKey() {
return core.implGenerateKey();
}
}
// nested static class for the ChaCha20 key generator
public static final class ChaCha20KeyGenerator extends KeyGeneratorSpi {
private final KeyGeneratorCore core;
public ChaCha20KeyGenerator() {
core = new KeyGeneratorCore("ChaCha20", 256);
}
@Override
protected void engineInit(SecureRandom random) {
core.implInit(random);
}
@Override
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
core.implInit(params, random);
}
@Override
protected void engineInit(int keySize, SecureRandom random) {
if (keySize != 256) {
throw new InvalidParameterException(
"Key length for ChaCha20 must be 256 bits");
}
core.implInit(keySize, random);
}
@Override
protected SecretKey engineGenerateKey() {
return core.implGenerateKey();
}
}
}

View file

@ -0,0 +1,257 @@
/*
* Copyright (c) 2018, 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
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.crypto.provider;
import java.nio.ByteBuffer;
import java.security.Key;
import java.security.InvalidKeyException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Objects;
import sun.security.util.math.*;
import sun.security.util.math.intpoly.*;
/**
* This class represents the Poly1305 function defined in RFC 7539.
*
* This function is used in the implementation of ChaCha20/Poly1305
* AEAD mode.
*/
final class Poly1305 {
private static final int KEY_LENGTH = 32;
private static final int RS_LENGTH = KEY_LENGTH / 2;
private static final int BLOCK_LENGTH = 16;
private static final int TAG_LENGTH = 16;
private static final IntegerFieldModuloP ipl1305 =
new IntegerPolynomial1305();
private byte[] keyBytes;
private final byte[] block = new byte[BLOCK_LENGTH];
private int blockOffset;
private IntegerModuloP r;
private IntegerModuloP s;
private MutableIntegerModuloP a;
private final MutableIntegerModuloP n = ipl1305.get1().mutable();
Poly1305() { }
/**
* Initialize the Poly1305 object
*
* @param newKey the {@code Key} which will be used for the authentication.
* @param params this parameter is unused.
*
* @throws InvalidKeyException if {@code newKey} is {@code null} or is
* not 32 bytes in length.
*/
void engineInit(Key newKey, AlgorithmParameterSpec params)
throws InvalidKeyException {
Objects.requireNonNull(newKey, "Null key provided during init");
keyBytes = newKey.getEncoded();
if (keyBytes == null) {
throw new InvalidKeyException("Key does not support encoding");
} else if (keyBytes.length != KEY_LENGTH) {
throw new InvalidKeyException("Incorrect length for key: " +
keyBytes.length);
}
engineReset();
setRSVals();
}
/**
* Returns the length of the MAC (authentication tag).
*
* @return the length of the auth tag, which is always 16 bytes.
*/
int engineGetMacLength() {
return TAG_LENGTH;
}
/**
* Reset the Poly1305 object, discarding any current operation but
* maintaining the same key.
*/
void engineReset() {
// Clear the block and reset the offset
Arrays.fill(block, (byte)0);
blockOffset = 0;
// Discard any previous accumulator and start at zero
a = ipl1305.get0().mutable();
}
/**
* Update the MAC with bytes from a {@code ByteBuffer}
*
* @param buf the {@code ByteBuffer} containing the data to be consumed.
* Upon return the buffer's position will be equal to its limit.
*/
void engineUpdate(ByteBuffer buf) {
int remaining = buf.remaining();
while (remaining > 0) {
int bytesToWrite = Integer.min(remaining,
BLOCK_LENGTH - blockOffset);
if (bytesToWrite >= BLOCK_LENGTH) {
// If bytes to write == BLOCK_LENGTH, then we have no
// left-over data from previous updates and we can create
// the IntegerModuloP directly from the input buffer.
processBlock(buf, bytesToWrite);
} else {
// We have some left-over data from previous updates, so
// copy that into the holding block until we get a full block.
buf.get(block, blockOffset, bytesToWrite);
blockOffset += bytesToWrite;
if (blockOffset >= BLOCK_LENGTH) {
processBlock(block, 0, BLOCK_LENGTH);
blockOffset = 0;
}
}
remaining -= bytesToWrite;
}
}
/**
* Update the MAC with bytes from an array.
*
* @param input the input bytes.
* @param offset the starting index from which to update the MAC.
* @param len the number of bytes to process.
*/
void engineUpdate(byte[] input, int offset, int len) {
Objects.checkFromIndexSize(offset, len, input.length);
if (blockOffset > 0) {
// We have some left-over data from previous updates
int blockSpaceLeft = BLOCK_LENGTH - blockOffset;
if (len < blockSpaceLeft) {
System.arraycopy(input, offset, block, blockOffset, len);
blockOffset += len;
return; // block wasn't filled
} else {
System.arraycopy(input, offset, block, blockOffset,
blockSpaceLeft);
offset += blockSpaceLeft;
len -= blockSpaceLeft;
processBlock(block, 0, BLOCK_LENGTH);
blockOffset = 0;
}
}
while (len >= BLOCK_LENGTH) {
processBlock(input, offset, BLOCK_LENGTH);
offset += BLOCK_LENGTH;
len -= BLOCK_LENGTH;
}
if (len > 0) { // and len < BLOCK_LENGTH
System.arraycopy(input, offset, block, 0, len);
blockOffset = len;
}
}
/**
* Update the MAC with a single byte of input
*
* @param input the byte to update the MAC with.
*/
void engineUpdate(byte input) {
assert (blockOffset < BLOCK_LENGTH);
// we can't hold fully filled unprocessed block
block[blockOffset++] = input;
if (blockOffset == BLOCK_LENGTH) {
processBlock(block, 0, BLOCK_LENGTH);
blockOffset = 0;
}
}
/**
* Finish the authentication operation and reset the MAC for a new
* authentication operation.
*
* @return the authentication tag as a byte array.
*/
byte[] engineDoFinal() {
byte[] tag = new byte[BLOCK_LENGTH];
// Finish up: process any remaining data < BLOCK_SIZE, then
// create the tag from the resulting little-endian integer.
if (blockOffset > 0) {
processBlock(block, 0, blockOffset);
blockOffset = 0;
}
// Add in the s-half of the key to the accumulator
a.addModPowerTwo(s, tag);
// Reset for the next auth
engineReset();
return tag;
}
/**
* Process a single block of data. This should only be called
* when the block array is complete. That may not necessarily
* be a full 16 bytes if the last block has less than 16 bytes.
*/
private void processBlock(ByteBuffer buf, int len) {
n.setValue(buf, len, (byte)0x01);
a.setSum(n); // a += (n | 0x01)
a.setProduct(r); // a = (a * r) % p
}
private void processBlock(byte[] block, int offset, int length) {
Objects.checkFromIndexSize(offset, length, block.length);
n.setValue(block, offset, length, (byte)0x01);
a.setSum(n); // a += (n | 0x01)
a.setProduct(r); // a = (a * r) % p
}
/**
* Partition the authentication key into the R and S components, clamp
* the R value, and instantiate IntegerModuloP objects to R and S's
* numeric values.
*/
private void setRSVals() {
// Clamp the bytes in the "r" half of the key.
keyBytes[3] &= 15;
keyBytes[7] &= 15;
keyBytes[11] &= 15;
keyBytes[15] &= 15;
keyBytes[4] &= 252;
keyBytes[8] &= 252;
keyBytes[12] &= 252;
// Create IntegerModuloP elements from the r and s values
r = ipl1305.getElement(keyBytes, 0, RS_LENGTH, (byte)0);
s = ipl1305.getElement(keyBytes, RS_LENGTH, RS_LENGTH, (byte)0);
}
}

View file

@ -57,6 +57,8 @@ import static sun.security.util.SecurityConstants.PROVIDER_VER;
*
* - ARCFOUR (RC4 compatible)
*
* - ChaCha20 (Stream cipher only and in AEAD mode with Poly1305)
*
* - Cipher modes ECB, CBC, CFB, OFB, PCBC, CTR, and CTS for all block ciphers
* and mode GCM for AES cipher
*
@ -77,7 +79,7 @@ public final class SunJCE extends Provider {
private static final String info = "SunJCE Provider " +
"(implements RSA, DES, Triple DES, AES, Blowfish, ARCFOUR, RC2, PBE, "
+ "Diffie-Hellman, HMAC)";
+ "Diffie-Hellman, HMAC, ChaCha20)";
private static final String OID_PKCS12_RC4_128 = "1.2.840.113549.1.12.1.1";
private static final String OID_PKCS12_RC4_40 = "1.2.840.113549.1.12.1.2";
@ -336,6 +338,15 @@ public final class SunJCE extends Provider {
put("Cipher.ARCFOUR SupportedPaddings", "NOPADDING");
put("Cipher.ARCFOUR SupportedKeyFormats", "RAW");
put("Cipher.ChaCha20",
"com.sun.crypto.provider.ChaCha20Cipher$ChaCha20Only");
put("Cipher.ChaCha20 SupportedKeyFormats", "RAW");
put("Cipher.ChaCha20-Poly1305",
"com.sun.crypto.provider.ChaCha20Cipher$ChaCha20Poly1305");
put("Cipher.ChaCha20-Poly1305 SupportedKeyFormats", "RAW");
put("Alg.Alias.Cipher.1.2.840.113549.1.9.16.3.18", "ChaCha20-Poly1305");
put("Alg.Alias.Cipher.OID.1.2.840.113549.1.9.16.3.18", "ChaCha20-Poly1305");
/*
* Key(pair) Generator engines
*/
@ -361,6 +372,10 @@ public final class SunJCE extends Provider {
"ARCFOURKeyGenerator");
put("Alg.Alias.KeyGenerator.RC4", "ARCFOUR");
put("KeyGenerator.ChaCha20",
"com.sun.crypto.provider.KeyGeneratorCore$" +
"ChaCha20KeyGenerator");
put("KeyGenerator.HmacMD5",
"com.sun.crypto.provider.HmacMD5KeyGenerator");
@ -541,6 +556,9 @@ public final class SunJCE extends Provider {
put("AlgorithmParameters.OAEP",
"com.sun.crypto.provider.OAEPParameters");
put("AlgorithmParameters.ChaCha20-Poly1305",
"com.sun.crypto.provider.ChaCha20Poly1305Parameters");
/*
* Key factories
*/