Path: blob/master/src/java.base/share/classes/com/sun/crypto/provider/DHKeyAgreement.java
41161 views
/*1* Copyright (c) 1997, 2021, 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 com.sun.crypto.provider;2627import java.util.*;28import java.lang.*;29import java.math.BigInteger;30import java.security.AccessController;31import java.security.InvalidAlgorithmParameterException;32import java.security.InvalidKeyException;33import java.security.Key;34import java.security.NoSuchAlgorithmException;35import java.security.SecureRandom;36import java.security.PrivilegedAction;37import java.security.ProviderException;38import java.security.spec.AlgorithmParameterSpec;39import java.security.spec.InvalidKeySpecException;40import javax.crypto.KeyAgreementSpi;41import javax.crypto.ShortBufferException;42import javax.crypto.SecretKey;43import javax.crypto.spec.*;4445import sun.security.util.KeyUtil;4647/**48* This class implements the Diffie-Hellman key agreement protocol between49* any number of parties.50*51* @author Jan Luehe52*53*/5455public final class DHKeyAgreement56extends KeyAgreementSpi {5758private boolean generateSecret = false;59private BigInteger init_p = null;60private BigInteger init_g = null;61private BigInteger x = BigInteger.ZERO; // the private value62private BigInteger y = BigInteger.ZERO;6364private static class AllowKDF {6566private static final boolean VALUE = getValue();6768@SuppressWarnings("removal")69private static boolean getValue() {70return AccessController.doPrivileged(71(PrivilegedAction<Boolean>)72() -> Boolean.getBoolean("jdk.crypto.KeyAgreement.legacyKDF"));73}74}7576/**77* Empty constructor78*/79public DHKeyAgreement() {80}8182/**83* Initializes this key agreement with the given key and source of84* randomness. The given key is required to contain all the algorithm85* parameters required for this key agreement.86*87* <p> If the key agreement algorithm requires random bytes, it gets them88* from the given source of randomness, <code>random</code>.89* However, if the underlying90* algorithm implementation does not require any random bytes,91* <code>random</code> is ignored.92*93* @param key the party's private information. For example, in the case94* of the Diffie-Hellman key agreement, this would be the party's own95* Diffie-Hellman private key.96* @param random the source of randomness97*98* @exception InvalidKeyException if the given key is99* inappropriate for this key agreement, e.g., is of the wrong type or100* has an incompatible algorithm type.101*/102protected void engineInit(Key key, SecureRandom random)103throws InvalidKeyException104{105try {106engineInit(key, null, random);107} catch (InvalidAlgorithmParameterException e) {108// never happens, because we did not pass any parameters109}110}111112/**113* Initializes this key agreement with the given key, set of114* algorithm parameters, and source of randomness.115*116* @param key the party's private information. For example, in the case117* of the Diffie-Hellman key agreement, this would be the party's own118* Diffie-Hellman private key.119* @param params the key agreement parameters120* @param random the source of randomness121*122* @exception InvalidKeyException if the given key is123* inappropriate for this key agreement, e.g., is of the wrong type or124* has an incompatible algorithm type.125* @exception InvalidAlgorithmParameterException if the given parameters126* are inappropriate for this key agreement.127*/128protected void engineInit(Key key, AlgorithmParameterSpec params,129SecureRandom random)130throws InvalidKeyException, InvalidAlgorithmParameterException131{132// ignore "random" parameter, because our implementation does not133// require any source of randomness134generateSecret = false;135init_p = null;136init_g = null;137138if ((params != null) && !(params instanceof DHParameterSpec)) {139throw new InvalidAlgorithmParameterException140("Diffie-Hellman parameters expected");141}142if (!(key instanceof javax.crypto.interfaces.DHPrivateKey)) {143throw new InvalidKeyException("Diffie-Hellman private key "144+ "expected");145}146javax.crypto.interfaces.DHPrivateKey dhPrivKey;147dhPrivKey = (javax.crypto.interfaces.DHPrivateKey)key;148149// check if private key parameters are compatible with150// initialized ones151if (params != null) {152init_p = ((DHParameterSpec)params).getP();153init_g = ((DHParameterSpec)params).getG();154}155BigInteger priv_p = dhPrivKey.getParams().getP();156BigInteger priv_g = dhPrivKey.getParams().getG();157if (init_p != null && priv_p != null && !(init_p.equals(priv_p))) {158throw new InvalidKeyException("Incompatible parameters");159}160if (init_g != null && priv_g != null && !(init_g.equals(priv_g))) {161throw new InvalidKeyException("Incompatible parameters");162}163if ((init_p == null && priv_p == null)164|| (init_g == null && priv_g == null)) {165throw new InvalidKeyException("Missing parameters");166}167init_p = priv_p;168init_g = priv_g;169170// store the x value171this.x = dhPrivKey.getX();172}173174/**175* Executes the next phase of this key agreement with the given176* key that was received from one of the other parties involved in this key177* agreement.178*179* @param key the key for this phase. For example, in the case of180* Diffie-Hellman between 2 parties, this would be the other party's181* Diffie-Hellman public key.182* @param lastPhase flag which indicates whether or not this is the last183* phase of this key agreement.184*185* @return the (intermediate) key resulting from this phase, or null if186* this phase does not yield a key187*188* @exception InvalidKeyException if the given key is inappropriate for189* this phase.190* @exception IllegalStateException if this key agreement has not been191* initialized.192*/193protected Key engineDoPhase(Key key, boolean lastPhase)194throws InvalidKeyException, IllegalStateException195{196if (!(key instanceof javax.crypto.interfaces.DHPublicKey)) {197throw new InvalidKeyException("Diffie-Hellman public key "198+ "expected");199}200javax.crypto.interfaces.DHPublicKey dhPubKey;201dhPubKey = (javax.crypto.interfaces.DHPublicKey)key;202203if (init_p == null || init_g == null) {204throw new IllegalStateException("Not initialized");205}206207// check if public key parameters are compatible with208// initialized ones209BigInteger pub_p = dhPubKey.getParams().getP();210BigInteger pub_g = dhPubKey.getParams().getG();211if (pub_p != null && !(init_p.equals(pub_p))) {212throw new InvalidKeyException("Incompatible parameters");213}214if (pub_g != null && !(init_g.equals(pub_g))) {215throw new InvalidKeyException("Incompatible parameters");216}217218// validate the Diffie-Hellman public key219KeyUtil.validate(dhPubKey);220221// store the y value222this.y = dhPubKey.getY();223224// we've received a public key (from one of the other parties),225// so we are ready to create the secret, which may be an226// intermediate secret, in which case we wrap it into a227// Diffie-Hellman public key object and return it.228generateSecret = true;229if (lastPhase == false) {230byte[] intermediate = engineGenerateSecret();231return new DHPublicKey(new BigInteger(1, intermediate),232init_p, init_g);233} else {234return null;235}236}237238/**239* Generates the shared secret and returns it in a new buffer.240*241* <p>This method resets this <code>KeyAgreementSpi</code> object,242* so that it243* can be reused for further key agreements. Unless this key agreement is244* reinitialized with one of the <code>engineInit</code> methods, the same245* private information and algorithm parameters will be used for246* subsequent key agreements.247*248* @return the new buffer with the shared secret249*250* @exception IllegalStateException if this key agreement has not been251* completed yet252*/253protected byte[] engineGenerateSecret()254throws IllegalStateException255{256int expectedLen = (init_p.bitLength() + 7) >>> 3;257byte[] result = new byte[expectedLen];258try {259engineGenerateSecret(result, 0);260} catch (ShortBufferException sbe) {261// should never happen since length are identical262}263return result;264}265266/**267* Generates the shared secret, and places it into the buffer268* <code>sharedSecret</code>, beginning at <code>offset</code>.269*270* <p>If the <code>sharedSecret</code> buffer is too small to hold the271* result, a <code>ShortBufferException</code> is thrown.272* In this case, this call should be repeated with a larger output buffer.273*274* <p>This method resets this <code>KeyAgreementSpi</code> object,275* so that it276* can be reused for further key agreements. Unless this key agreement is277* reinitialized with one of the <code>engineInit</code> methods, the same278* private information and algorithm parameters will be used for279* subsequent key agreements.280*281* @param sharedSecret the buffer for the shared secret282* @param offset the offset in <code>sharedSecret</code> where the283* shared secret will be stored284*285* @return the number of bytes placed into <code>sharedSecret</code>286*287* @exception IllegalStateException if this key agreement has not been288* completed yet289* @exception ShortBufferException if the given output buffer is too small290* to hold the secret291*/292protected int engineGenerateSecret(byte[] sharedSecret, int offset)293throws IllegalStateException, ShortBufferException294{295if (generateSecret == false) {296throw new IllegalStateException297("Key agreement has not been completed yet");298}299300if (sharedSecret == null) {301throw new ShortBufferException302("No buffer provided for shared secret");303}304305BigInteger modulus = init_p;306int expectedLen = (modulus.bitLength() + 7) >>> 3;307if ((sharedSecret.length - offset) < expectedLen) {308throw new ShortBufferException309("Buffer too short for shared secret");310}311312// Reset the key agreement after checking for ShortBufferException313// above, so user can recover w/o losing internal state314generateSecret = false;315316// No further process if z <= 1 or z == (p - 1) (See section 5.7.1,317// NIST SP 800-56A Rev 3).318BigInteger z = this.y.modPow(this.x, modulus);319if ((z.compareTo(BigInteger.ONE) <= 0) ||320z.equals(modulus.subtract(BigInteger.ONE))) {321throw new ProviderException(322"Generated secret is out-of-range of (1, p -1)");323}324325/*326* NOTE: BigInteger.toByteArray() returns a byte array containing327* the two's-complement representation of this BigInteger with328* the most significant byte is in the zeroth element. This329* contains the minimum number of bytes required to represent330* this BigInteger, including at least one sign bit whose value331* is always 0.332*333* Keys are always positive, and the above sign bit isn't334* actually used when representing keys. (i.e. key = new335* BigInteger(1, byteArray)) To obtain an array containing336* exactly expectedLen bytes of magnitude, we strip any extra337* leading 0's, or pad with 0's in case of a "short" secret.338*/339byte[] secret = z.toByteArray();340if (secret.length == expectedLen) {341System.arraycopy(secret, 0, sharedSecret, offset,342secret.length);343} else {344// Array too short, pad it w/ leading 0s345if (secret.length < expectedLen) {346System.arraycopy(secret, 0, sharedSecret,347offset + (expectedLen - secret.length),348secret.length);349} else {350// Array too long, check and trim off the excess351if ((secret.length == (expectedLen+1)) && secret[0] == 0) {352// ignore the leading sign byte353System.arraycopy(secret, 1, sharedSecret, offset, expectedLen);354} else {355throw new ProviderException("Generated secret is out-of-range");356}357}358}359return expectedLen;360}361362/**363* Creates the shared secret and returns it as a secret key object364* of the requested algorithm type.365*366* <p>This method resets this <code>KeyAgreementSpi</code> object,367* so that it368* can be reused for further key agreements. Unless this key agreement is369* reinitialized with one of the <code>engineInit</code> methods, the same370* private information and algorithm parameters will be used for371* subsequent key agreements.372*373* @param algorithm the requested secret key algorithm374*375* @return the shared secret key376*377* @exception IllegalStateException if this key agreement has not been378* completed yet379* @exception NoSuchAlgorithmException if the requested secret key380* algorithm is not available381* @exception InvalidKeyException if the shared secret key material cannot382* be used to generate a secret key of the requested algorithm type (e.g.,383* the key material is too short)384*/385protected SecretKey engineGenerateSecret(String algorithm)386throws IllegalStateException, NoSuchAlgorithmException,387InvalidKeyException388{389if (algorithm == null) {390throw new NoSuchAlgorithmException("null algorithm");391}392393if (!algorithm.equalsIgnoreCase("TlsPremasterSecret") &&394!AllowKDF.VALUE) {395396throw new NoSuchAlgorithmException("Unsupported secret key "397+ "algorithm: " + algorithm);398}399400byte[] secret = engineGenerateSecret();401if (algorithm.equalsIgnoreCase("DES")) {402// DES403return new DESKey(secret);404} else if (algorithm.equalsIgnoreCase("DESede")405|| algorithm.equalsIgnoreCase("TripleDES")) {406// Triple DES407return new DESedeKey(secret);408} else if (algorithm.equalsIgnoreCase("Blowfish")) {409// Blowfish410int keysize = secret.length;411if (keysize >= BlowfishConstants.BLOWFISH_MAX_KEYSIZE)412keysize = BlowfishConstants.BLOWFISH_MAX_KEYSIZE;413SecretKeySpec skey = new SecretKeySpec(secret, 0, keysize,414"Blowfish");415return skey;416} else if (algorithm.equalsIgnoreCase("AES")) {417// AES418int keysize = secret.length;419SecretKeySpec skey = null;420int idx = AESConstants.AES_KEYSIZES.length - 1;421while (skey == null && idx >= 0) {422// Generate the strongest key using the shared secret423// assuming the key sizes in AESConstants class are424// in ascending order425if (keysize >= AESConstants.AES_KEYSIZES[idx]) {426keysize = AESConstants.AES_KEYSIZES[idx];427skey = new SecretKeySpec(secret, 0, keysize, "AES");428}429idx--;430}431if (skey == null) {432throw new InvalidKeyException("Key material is too short");433}434return skey;435} else if (algorithm.equals("TlsPremasterSecret")) {436// remove leading zero bytes per RFC 5246 Section 8.1.2437return new SecretKeySpec(438KeyUtil.trimZeroes(secret), "TlsPremasterSecret");439} else {440throw new NoSuchAlgorithmException("Unsupported secret key "441+ "algorithm: "+ algorithm);442}443}444}445446447