Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/com/sun/crypto/provider/DHKeyAgreement.java
38922 views
/*1* Copyright (c) 1997, 2017, 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();6768private static boolean getValue() {69return AccessController.doPrivileged(70(PrivilegedAction<Boolean>)71() -> Boolean.getBoolean("jdk.crypto.KeyAgreement.legacyKDF"));72}73}7475/**76* Empty constructor77*/78public DHKeyAgreement() {79}8081/**82* Initializes this key agreement with the given key and source of83* randomness. The given key is required to contain all the algorithm84* parameters required for this key agreement.85*86* <p> If the key agreement algorithm requires random bytes, it gets them87* from the given source of randomness, <code>random</code>.88* However, if the underlying89* algorithm implementation does not require any random bytes,90* <code>random</code> is ignored.91*92* @param key the party's private information. For example, in the case93* of the Diffie-Hellman key agreement, this would be the party's own94* Diffie-Hellman private key.95* @param random the source of randomness96*97* @exception InvalidKeyException if the given key is98* inappropriate for this key agreement, e.g., is of the wrong type or99* has an incompatible algorithm type.100*/101protected void engineInit(Key key, SecureRandom random)102throws InvalidKeyException103{104try {105engineInit(key, null, random);106} catch (InvalidAlgorithmParameterException e) {107// never happens, because we did not pass any parameters108}109}110111/**112* Initializes this key agreement with the given key, set of113* algorithm parameters, and source of randomness.114*115* @param key the party's private information. For example, in the case116* of the Diffie-Hellman key agreement, this would be the party's own117* Diffie-Hellman private key.118* @param params the key agreement parameters119* @param random the source of randomness120*121* @exception InvalidKeyException if the given key is122* inappropriate for this key agreement, e.g., is of the wrong type or123* has an incompatible algorithm type.124* @exception InvalidAlgorithmParameterException if the given parameters125* are inappropriate for this key agreement.126*/127protected void engineInit(Key key, AlgorithmParameterSpec params,128SecureRandom random)129throws InvalidKeyException, InvalidAlgorithmParameterException130{131// ignore "random" parameter, because our implementation does not132// require any source of randomness133generateSecret = false;134init_p = null;135init_g = null;136137if ((params != null) && !(params instanceof DHParameterSpec)) {138throw new InvalidAlgorithmParameterException139("Diffie-Hellman parameters expected");140}141if (!(key instanceof javax.crypto.interfaces.DHPrivateKey)) {142throw new InvalidKeyException("Diffie-Hellman private key "143+ "expected");144}145javax.crypto.interfaces.DHPrivateKey dhPrivKey;146dhPrivKey = (javax.crypto.interfaces.DHPrivateKey)key;147148// check if private key parameters are compatible with149// initialized ones150if (params != null) {151init_p = ((DHParameterSpec)params).getP();152init_g = ((DHParameterSpec)params).getG();153}154BigInteger priv_p = dhPrivKey.getParams().getP();155BigInteger priv_g = dhPrivKey.getParams().getG();156if (init_p != null && priv_p != null && !(init_p.equals(priv_p))) {157throw new InvalidKeyException("Incompatible parameters");158}159if (init_g != null && priv_g != null && !(init_g.equals(priv_g))) {160throw new InvalidKeyException("Incompatible parameters");161}162if ((init_p == null && priv_p == null)163|| (init_g == null && priv_g == null)) {164throw new InvalidKeyException("Missing parameters");165}166init_p = priv_p;167init_g = priv_g;168169// store the x value170this.x = dhPrivKey.getX();171}172173/**174* Executes the next phase of this key agreement with the given175* key that was received from one of the other parties involved in this key176* agreement.177*178* @param key the key for this phase. For example, in the case of179* Diffie-Hellman between 2 parties, this would be the other party's180* Diffie-Hellman public key.181* @param lastPhase flag which indicates whether or not this is the last182* phase of this key agreement.183*184* @return the (intermediate) key resulting from this phase, or null if185* this phase does not yield a key186*187* @exception InvalidKeyException if the given key is inappropriate for188* this phase.189* @exception IllegalStateException if this key agreement has not been190* initialized.191*/192protected Key engineDoPhase(Key key, boolean lastPhase)193throws InvalidKeyException, IllegalStateException194{195if (!(key instanceof javax.crypto.interfaces.DHPublicKey)) {196throw new InvalidKeyException("Diffie-Hellman public key "197+ "expected");198}199javax.crypto.interfaces.DHPublicKey dhPubKey;200dhPubKey = (javax.crypto.interfaces.DHPublicKey)key;201202if (init_p == null || init_g == null) {203throw new IllegalStateException("Not initialized");204}205206// check if public key parameters are compatible with207// initialized ones208BigInteger pub_p = dhPubKey.getParams().getP();209BigInteger pub_g = dhPubKey.getParams().getG();210if (pub_p != null && !(init_p.equals(pub_p))) {211throw new InvalidKeyException("Incompatible parameters");212}213if (pub_g != null && !(init_g.equals(pub_g))) {214throw new InvalidKeyException("Incompatible parameters");215}216217// validate the Diffie-Hellman public key218KeyUtil.validate(dhPubKey);219220// store the y value221this.y = dhPubKey.getY();222223// we've received a public key (from one of the other parties),224// so we are ready to create the secret, which may be an225// intermediate secret, in which case we wrap it into a226// Diffie-Hellman public key object and return it.227generateSecret = true;228if (lastPhase == false) {229byte[] intermediate = engineGenerateSecret();230return new DHPublicKey(new BigInteger(1, intermediate),231init_p, init_g);232} else {233return null;234}235}236237/**238* Generates the shared secret and returns it in a new buffer.239*240* <p>This method resets this <code>KeyAgreementSpi</code> object,241* so that it242* can be reused for further key agreements. Unless this key agreement is243* reinitialized with one of the <code>engineInit</code> methods, the same244* private information and algorithm parameters will be used for245* subsequent key agreements.246*247* @return the new buffer with the shared secret248*249* @exception IllegalStateException if this key agreement has not been250* completed yet251*/252protected byte[] engineGenerateSecret()253throws IllegalStateException254{255int expectedLen = (init_p.bitLength() + 7) >>> 3;256byte[] result = new byte[expectedLen];257try {258engineGenerateSecret(result, 0);259} catch (ShortBufferException sbe) {260// should never happen since length are identical261}262return result;263}264265/**266* Generates the shared secret, and places it into the buffer267* <code>sharedSecret</code>, beginning at <code>offset</code>.268*269* <p>If the <code>sharedSecret</code> buffer is too small to hold the270* result, a <code>ShortBufferException</code> is thrown.271* In this case, this call should be repeated with a larger output buffer.272*273* <p>This method resets this <code>KeyAgreementSpi</code> object,274* so that it275* can be reused for further key agreements. Unless this key agreement is276* reinitialized with one of the <code>engineInit</code> methods, the same277* private information and algorithm parameters will be used for278* subsequent key agreements.279*280* @param sharedSecret the buffer for the shared secret281* @param offset the offset in <code>sharedSecret</code> where the282* shared secret will be stored283*284* @return the number of bytes placed into <code>sharedSecret</code>285*286* @exception IllegalStateException if this key agreement has not been287* completed yet288* @exception ShortBufferException if the given output buffer is too small289* to hold the secret290*/291protected int engineGenerateSecret(byte[] sharedSecret, int offset)292throws IllegalStateException, ShortBufferException293{294if (generateSecret == false) {295throw new IllegalStateException296("Key agreement has not been completed yet");297}298299if (sharedSecret == null) {300throw new ShortBufferException301("No buffer provided for shared secret");302}303304BigInteger modulus = init_p;305int expectedLen = (modulus.bitLength() + 7) >>> 3;306if ((sharedSecret.length - offset) < expectedLen) {307throw new ShortBufferException308("Buffer too short for shared secret");309}310311// Reset the key agreement after checking for ShortBufferException312// above, so user can recover w/o losing internal state313generateSecret = false;314315/*316* NOTE: BigInteger.toByteArray() returns a byte array containing317* the two's-complement representation of this BigInteger with318* the most significant byte is in the zeroth element. This319* contains the minimum number of bytes required to represent320* this BigInteger, including at least one sign bit whose value321* is always 0.322*323* Keys are always positive, and the above sign bit isn't324* actually used when representing keys. (i.e. key = new325* BigInteger(1, byteArray)) To obtain an array containing326* exactly expectedLen bytes of magnitude, we strip any extra327* leading 0's, or pad with 0's in case of a "short" secret.328*/329byte[] secret = this.y.modPow(this.x, modulus).toByteArray();330if (secret.length == expectedLen) {331System.arraycopy(secret, 0, sharedSecret, offset,332secret.length);333} else {334// Array too short, pad it w/ leading 0s335if (secret.length < expectedLen) {336System.arraycopy(secret, 0, sharedSecret,337offset + (expectedLen - secret.length),338secret.length);339} else {340// Array too long, check and trim off the excess341if ((secret.length == (expectedLen+1)) && secret[0] == 0) {342// ignore the leading sign byte343System.arraycopy(secret, 1, sharedSecret, offset, expectedLen);344} else {345throw new ProviderException("Generated secret is out-of-range");346}347}348}349return expectedLen;350}351352/**353* Creates the shared secret and returns it as a secret key object354* of the requested algorithm type.355*356* <p>This method resets this <code>KeyAgreementSpi</code> object,357* so that it358* can be reused for further key agreements. Unless this key agreement is359* reinitialized with one of the <code>engineInit</code> methods, the same360* private information and algorithm parameters will be used for361* subsequent key agreements.362*363* @param algorithm the requested secret key algorithm364*365* @return the shared secret key366*367* @exception IllegalStateException if this key agreement has not been368* completed yet369* @exception NoSuchAlgorithmException if the requested secret key370* algorithm is not available371* @exception InvalidKeyException if the shared secret key material cannot372* be used to generate a secret key of the requested algorithm type (e.g.,373* the key material is too short)374*/375protected SecretKey engineGenerateSecret(String algorithm)376throws IllegalStateException, NoSuchAlgorithmException,377InvalidKeyException378{379if (algorithm == null) {380throw new NoSuchAlgorithmException("null algorithm");381}382383if (!algorithm.equalsIgnoreCase("TlsPremasterSecret") &&384!AllowKDF.VALUE) {385386throw new NoSuchAlgorithmException("Unsupported secret key "387+ "algorithm: " + algorithm);388}389390byte[] secret = engineGenerateSecret();391if (algorithm.equalsIgnoreCase("DES")) {392// DES393return new DESKey(secret);394} else if (algorithm.equalsIgnoreCase("DESede")395|| algorithm.equalsIgnoreCase("TripleDES")) {396// Triple DES397return new DESedeKey(secret);398} else if (algorithm.equalsIgnoreCase("Blowfish")) {399// Blowfish400int keysize = secret.length;401if (keysize >= BlowfishConstants.BLOWFISH_MAX_KEYSIZE)402keysize = BlowfishConstants.BLOWFISH_MAX_KEYSIZE;403SecretKeySpec skey = new SecretKeySpec(secret, 0, keysize,404"Blowfish");405return skey;406} else if (algorithm.equalsIgnoreCase("AES")) {407// AES408int keysize = secret.length;409SecretKeySpec skey = null;410int idx = AESConstants.AES_KEYSIZES.length - 1;411while (skey == null && idx >= 0) {412// Generate the strongest key using the shared secret413// assuming the key sizes in AESConstants class are414// in ascending order415if (keysize >= AESConstants.AES_KEYSIZES[idx]) {416keysize = AESConstants.AES_KEYSIZES[idx];417skey = new SecretKeySpec(secret, 0, keysize, "AES");418}419idx--;420}421if (skey == null) {422throw new InvalidKeyException("Key material is too short");423}424return skey;425} else if (algorithm.equals("TlsPremasterSecret")) {426// remove leading zero bytes per RFC 5246 Section 8.1.2427return new SecretKeySpec(428KeyUtil.trimZeroes(secret), "TlsPremasterSecret");429} else {430throw new NoSuchAlgorithmException("Unsupported secret key "431+ "algorithm: "+ algorithm);432}433}434}435436437