Path: blob/master/src/java.base/share/classes/sun/security/ssl/HKDF.java
41159 views
/*1* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.ssl;2627import java.security.NoSuchAlgorithmException;28import java.security.InvalidKeyException;29import javax.crypto.Mac;30import javax.crypto.SecretKey;31import javax.crypto.ShortBufferException;32import javax.crypto.spec.SecretKeySpec;33import java.util.Objects;3435/**36* An implementation of the HKDF key derivation algorithm outlined in RFC 5869,37* specific to the needs of TLS 1.3 key derivation in JSSE. This is not a38* general purpose HKDF implementation and is suited only to single-key output39* derivations.40*41* HKDF objects are created by specifying a message digest algorithm. That42* digest algorithm will be used by the HMAC function as part of the HKDF43* derivation process.44*/45final class HKDF {46private final Mac hmacObj;47private final int hmacLen;4849/**50* Create an HDKF object, specifying the underlying message digest51* algorithm.52*53* @param hashAlg a standard name corresponding to a supported message54* digest algorithm.55*56* @throws NoSuchAlgorithmException if that message digest algorithm does57* not have an HMAC variant supported on any available provider.58*/59HKDF(String hashAlg) throws NoSuchAlgorithmException {60Objects.requireNonNull(hashAlg,61"Must provide underlying HKDF Digest algorithm.");62String hmacAlg = "Hmac" + hashAlg.replace("-", "");63hmacObj = Mac.getInstance(hmacAlg);64hmacLen = hmacObj.getMacLength();65}6667/**68* Perform the HMAC-Extract derivation.69*70* @param salt a salt value, implemented as a {@code SecretKey}. A71* {@code null} value is allowed, which will internally use an array of72* zero bytes the same size as the underlying hash output length.73* @param inputKey the input keying material provided as a74* {@code SecretKey}.75* @param keyAlg the algorithm name assigned to the resulting76* {@code SecretKey} object.77*78* @return a {@code SecretKey} that is the result of the HKDF extract79* operation.80*81* @throws InvalidKeyException if the {@code salt} parameter cannot be82* used to initialize the underlying HMAC.83*/84SecretKey extract(SecretKey salt, SecretKey inputKey, String keyAlg)85throws InvalidKeyException {86if (salt == null) {87salt = new SecretKeySpec(new byte[hmacLen], "HKDF-Salt");88}89hmacObj.init(salt);9091return new SecretKeySpec(hmacObj.doFinal(inputKey.getEncoded()),92keyAlg);93}9495/**96* Perform the HMAC-Extract derivation.97*98* @param salt a salt value as cleartext bytes. A {@code null} value is99* allowed, which will internally use an array of zero bytes the same100* size as the underlying hash output length.101* @param inputKey the input keying material provided as a102* {@code SecretKey}.103* @param keyAlg the algorithm name assigned to the resulting104* {@code SecretKey} object.105*106* @return a {@code SecretKey} that is the result of the HKDF extract107* operation.108*109* @throws InvalidKeyException if the {@code salt} parameter cannot be110* used to initialize the underlying HMAC.111*/112SecretKey extract(byte[] salt, SecretKey inputKey, String keyAlg)113throws InvalidKeyException {114if (salt == null) {115salt = new byte[hmacLen];116}117return extract(new SecretKeySpec(salt, "HKDF-Salt"), inputKey, keyAlg);118}119120/**121* Perform the HKDF-Expand derivation for a single-key output.122*123* @param pseudoRandKey the pseudo random key (PRK).124* @param info optional context-specific info. A {@code null} value is125* allowed in which case a zero-length byte array will be used.126* @param outLen the length of the resulting {@code SecretKey}127* @param keyAlg the algorithm name applied to the resulting128* {@code SecretKey}129*130* @return the resulting key derivation as a {@code SecretKey} object131*132* @throws InvalidKeyException if the underlying HMAC operation cannot133* be initialized using the provided {@code pseudoRandKey} object.134*/135SecretKey expand(SecretKey pseudoRandKey, byte[] info, int outLen,136String keyAlg) throws InvalidKeyException {137byte[] kdfOutput;138139// Calculate the number of rounds of HMAC that are needed to140// meet the requested data. Then set up the buffers we will need.141Objects.requireNonNull(pseudoRandKey, "A null PRK is not allowed.");142143// Output from the expand operation must be <= 255 * hmac length144if (outLen > 255 * hmacLen) {145throw new IllegalArgumentException("Requested output length " +146"exceeds maximum length allowed for HKDF expansion");147}148hmacObj.init(pseudoRandKey);149if (info == null) {150info = new byte[0];151}152int rounds = (outLen + hmacLen - 1) / hmacLen;153kdfOutput = new byte[rounds * hmacLen];154int offset = 0;155int tLength = 0;156157for (int i = 0; i < rounds ; i++) {158159// Calculate this round160try {161// Add T(i). This will be an empty string on the first162// iteration since tLength starts at zero. After the first163// iteration, tLength is changed to the HMAC length for the164// rest of the loop.165hmacObj.update(kdfOutput,166Math.max(0, offset - hmacLen), tLength);167hmacObj.update(info); // Add info168hmacObj.update((byte)(i + 1)); // Add round number169hmacObj.doFinal(kdfOutput, offset);170171tLength = hmacLen;172offset += hmacLen; // For next iteration173} catch (ShortBufferException sbe) {174// This really shouldn't happen given that we've175// sized the buffers to their largest possible size up-front,176// but just in case...177throw new RuntimeException(sbe);178}179}180181return new SecretKeySpec(kdfOutput, 0, outLen, keyAlg);182}183}184185186187