Path: blob/master/src/java.base/share/classes/javax/crypto/KeyAgreement.java
41152 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 javax.crypto;2627import java.util.*;2829import java.security.*;30import java.security.Provider.Service;31import java.security.spec.*;3233import sun.security.util.Debug;34import sun.security.jca.*;35import sun.security.jca.GetInstance.Instance;3637/**38* This class provides the functionality of a key agreement (or key39* exchange) protocol.40* <p>41* The keys involved in establishing a shared secret are created by one of the42* key generators ({@code KeyPairGenerator} or43* {@code KeyGenerator}), a {@code KeyFactory}, or as a result from44* an intermediate phase of the key agreement protocol.45*46* <p> For each of the correspondents in the key exchange, {@code doPhase}47* needs to be called. For example, if this key exchange is with one other48* party, {@code doPhase} needs to be called once, with the49* {@code lastPhase} flag set to {@code true}.50* If this key exchange is51* with two other parties, {@code doPhase} needs to be called twice,52* the first time setting the {@code lastPhase} flag to53* {@code false}, and the second time setting it to {@code true}.54* There may be any number of parties involved in a key exchange. However,55* support for key exchanges with more than two parties is implementation56* specific or as specified by the standard key agreement algorithm.57*58* <p> Every implementation of the Java platform is required to support the59* following standard {@code KeyAgreement} algorithm:60* <ul>61* <li>{@code DiffieHellman}</li>62* </ul>63* This algorithm is described in the <a href=64* "{@docRoot}/../specs/security/standard-names.html#keyagreement-algorithms">65* KeyAgreement section</a> of the66* Java Security Standard Algorithm Names Specification.67* Consult the release documentation for your implementation to see if any68* other algorithms are supported.69*70* @author Jan Luehe71*72* @see KeyGenerator73* @see SecretKey74* @since 1.475*/7677public class KeyAgreement {7879private static final Debug debug =80Debug.getInstance("jca", "KeyAgreement");8182private static final Debug pdebug =83Debug.getInstance("provider", "Provider");84private static final boolean skipDebug =85Debug.isOn("engine=") && !Debug.isOn("keyagreement");8687// The provider88private Provider provider;8990// The provider implementation (delegate)91private KeyAgreementSpi spi;9293// The name of the key agreement algorithm.94private final String algorithm;9596// next service to try in provider selection97// null once provider is selected98private Service firstService;99100// remaining services to try in provider selection101// null once provider is selected102private Iterator<Service> serviceIterator;103104private final Object lock;105106/**107* Creates a KeyAgreement object.108*109* @param keyAgreeSpi the delegate110* @param provider the provider111* @param algorithm the algorithm112*/113protected KeyAgreement(KeyAgreementSpi keyAgreeSpi, Provider provider,114String algorithm) {115this.spi = keyAgreeSpi;116this.provider = provider;117this.algorithm = algorithm;118lock = null;119}120121private KeyAgreement(Service s, Iterator<Service> t, String algorithm) {122firstService = s;123serviceIterator = t;124this.algorithm = algorithm;125lock = new Object();126}127128/**129* Returns the algorithm name of this {@code KeyAgreement} object.130*131* <p>This is the same name that was specified in one of the132* {@code getInstance} calls that created this133* {@code KeyAgreement} object.134*135* @return the algorithm name of this {@code KeyAgreement} object.136*/137public final String getAlgorithm() {138return this.algorithm;139}140141/**142* Returns a {@code KeyAgreement} object that implements the143* specified key agreement algorithm.144*145* <p> This method traverses the list of registered security Providers,146* starting with the most preferred Provider.147* A new KeyAgreement object encapsulating the148* KeyAgreementSpi implementation from the first149* Provider that supports the specified algorithm is returned.150*151* <p> Note that the list of registered providers may be retrieved via152* the {@link Security#getProviders() Security.getProviders()} method.153*154* @implNote155* The JDK Reference Implementation additionally uses the156* {@code jdk.security.provider.preferred}157* {@link Security#getProperty(String) Security} property to determine158* the preferred provider order for the specified algorithm. This159* may be different than the order of providers returned by160* {@link Security#getProviders() Security.getProviders()}.161*162* @param algorithm the standard name of the requested key agreement163* algorithm.164* See the KeyAgreement section in the <a href=165* "{@docRoot}/../specs/security/standard-names.html#keyagreement-algorithms">166* Java Security Standard Algorithm Names Specification</a>167* for information about standard algorithm names.168*169* @return the new {@code KeyAgreement} object170*171* @throws NoSuchAlgorithmException if no {@code Provider} supports a172* {@code KeyAgreementSpi} implementation for the173* specified algorithm174*175* @throws NullPointerException if {@code algorithm} is {@code null}176*177* @see java.security.Provider178*/179public static final KeyAgreement getInstance(String algorithm)180throws NoSuchAlgorithmException {181Objects.requireNonNull(algorithm, "null algorithm name");182List<Service> services =183GetInstance.getServices("KeyAgreement", algorithm);184// make sure there is at least one service from a signed provider185Iterator<Service> t = services.iterator();186while (t.hasNext()) {187Service s = t.next();188if (JceSecurity.canUseProvider(s.getProvider()) == false) {189continue;190}191return new KeyAgreement(s, t, algorithm);192}193throw new NoSuchAlgorithmException194("Algorithm " + algorithm + " not available");195}196197/**198* Returns a {@code KeyAgreement} object that implements the199* specified key agreement algorithm.200*201* <p> A new KeyAgreement object encapsulating the202* KeyAgreementSpi implementation from the specified provider203* is returned. The specified provider must be registered204* in the security provider list.205*206* <p> Note that the list of registered providers may be retrieved via207* the {@link Security#getProviders() Security.getProviders()} method.208*209* @param algorithm the standard name of the requested key agreement210* algorithm.211* See the KeyAgreement section in the <a href=212* "{@docRoot}/../specs/security/standard-names.html#keyagreement-algorithms">213* Java Security Standard Algorithm Names Specification</a>214* for information about standard algorithm names.215*216* @param provider the name of the provider.217*218* @return the new {@code KeyAgreement} object219*220* @throws IllegalArgumentException if the {@code provider}221* is {@code null} or empty222*223* @throws NoSuchAlgorithmException if a {@code KeyAgreementSpi}224* implementation for the specified algorithm is not225* available from the specified provider226*227* @throws NoSuchProviderException if the specified provider is not228* registered in the security provider list229*230* @throws NullPointerException if {@code algorithm} is {@code null}231*232* @see java.security.Provider233*/234public static final KeyAgreement getInstance(String algorithm,235String provider) throws NoSuchAlgorithmException,236NoSuchProviderException {237Objects.requireNonNull(algorithm, "null algorithm name");238Instance instance = JceSecurity.getInstance239("KeyAgreement", KeyAgreementSpi.class, algorithm, provider);240return new KeyAgreement((KeyAgreementSpi)instance.impl,241instance.provider, algorithm);242}243244/**245* Returns a {@code KeyAgreement} object that implements the246* specified key agreement algorithm.247*248* <p> A new KeyAgreement object encapsulating the249* KeyAgreementSpi implementation from the specified Provider250* object is returned. Note that the specified Provider object251* does not have to be registered in the provider list.252*253* @param algorithm the standard name of the requested key agreement254* algorithm.255* See the KeyAgreement section in the <a href=256* "{@docRoot}/../specs/security/standard-names.html#keyagreement-algorithms">257* Java Security Standard Algorithm Names Specification</a>258* for information about standard algorithm names.259*260* @param provider the provider.261*262* @return the new {@code KeyAgreement} object263*264* @throws IllegalArgumentException if the {@code provider}265* is {@code null}266*267* @throws NoSuchAlgorithmException if a {@code KeyAgreementSpi}268* implementation for the specified algorithm is not available269* from the specified Provider object270*271* @throws NullPointerException if {@code algorithm} is {@code null}272*273* @see java.security.Provider274*/275public static final KeyAgreement getInstance(String algorithm,276Provider provider) throws NoSuchAlgorithmException {277Objects.requireNonNull(algorithm, "null algorithm name");278Instance instance = JceSecurity.getInstance279("KeyAgreement", KeyAgreementSpi.class, algorithm, provider);280return new KeyAgreement((KeyAgreementSpi)instance.impl,281instance.provider, algorithm);282}283284// max number of debug warnings to print from chooseFirstProvider()285private static int warnCount = 10;286287/**288* Choose the Spi from the first provider available. Used if289* delayed provider selection is not possible because init()290* is not the first method called.291*/292void chooseFirstProvider() {293if (spi != null) {294return;295}296synchronized (lock) {297if (spi != null) {298return;299}300if (debug != null) {301int w = --warnCount;302if (w >= 0) {303debug.println("KeyAgreement.init() not first method "304+ "called, disabling delayed provider selection");305if (w == 0) {306debug.println("Further warnings of this type will "307+ "be suppressed");308}309new Exception("Call trace").printStackTrace();310}311}312Exception lastException = null;313while ((firstService != null) || serviceIterator.hasNext()) {314Service s;315if (firstService != null) {316s = firstService;317firstService = null;318} else {319s = serviceIterator.next();320}321if (JceSecurity.canUseProvider(s.getProvider()) == false) {322continue;323}324try {325Object obj = s.newInstance(null);326if (obj instanceof KeyAgreementSpi == false) {327continue;328}329spi = (KeyAgreementSpi)obj;330provider = s.getProvider();331// not needed any more332firstService = null;333serviceIterator = null;334return;335} catch (Exception e) {336lastException = e;337}338}339ProviderException e = new ProviderException340("Could not construct KeyAgreementSpi instance");341if (lastException != null) {342e.initCause(lastException);343}344throw e;345}346}347348private static final int I_NO_PARAMS = 1;349private static final int I_PARAMS = 2;350351private void implInit(KeyAgreementSpi spi, int type, Key key,352AlgorithmParameterSpec params, SecureRandom random)353throws InvalidKeyException, InvalidAlgorithmParameterException {354if (type == I_NO_PARAMS) {355spi.engineInit(key, random);356} else { // I_PARAMS357spi.engineInit(key, params, random);358}359}360361private void chooseProvider(int initType, Key key,362AlgorithmParameterSpec params, SecureRandom random)363throws InvalidKeyException, InvalidAlgorithmParameterException {364synchronized (lock) {365if (spi != null) {366implInit(spi, initType, key, params, random);367return;368}369Exception lastException = null;370while ((firstService != null) || serviceIterator.hasNext()) {371Service s;372if (firstService != null) {373s = firstService;374firstService = null;375} else {376s = serviceIterator.next();377}378// if provider says it does not support this key, ignore it379if (s.supportsParameter(key) == false) {380continue;381}382if (JceSecurity.canUseProvider(s.getProvider()) == false) {383continue;384}385try {386KeyAgreementSpi spi = (KeyAgreementSpi)s.newInstance(null);387implInit(spi, initType, key, params, random);388provider = s.getProvider();389this.spi = spi;390firstService = null;391serviceIterator = null;392return;393} catch (Exception e) {394// NoSuchAlgorithmException from newInstance()395// InvalidKeyException from init()396// RuntimeException (ProviderException) from init()397if (lastException == null) {398lastException = e;399}400}401}402// no working provider found, fail403if (lastException instanceof InvalidKeyException) {404throw (InvalidKeyException)lastException;405}406if (lastException instanceof InvalidAlgorithmParameterException) {407throw (InvalidAlgorithmParameterException)lastException;408}409if (lastException instanceof RuntimeException) {410throw (RuntimeException)lastException;411}412String kName = (key != null) ? key.getClass().getName() : "(null)";413throw new InvalidKeyException414("No installed provider supports this key: "415+ kName, lastException);416}417}418419/**420* Returns the provider of this {@code KeyAgreement} object.421*422* @return the provider of this {@code KeyAgreement} object423*/424public final Provider getProvider() {425chooseFirstProvider();426return this.provider;427}428429/**430* Initializes this key agreement with the given key, which is required to431* contain all the algorithm parameters required for this key agreement.432*433* <p> If this key agreement requires any random bytes, it will get434* them using the435* {@link java.security.SecureRandom}436* implementation of the highest-priority437* installed provider as the source of randomness.438* (If none of the installed providers supply an implementation of439* SecureRandom, a system-provided source of randomness will be used.)440*441* @param key the party's private information. For example, in the case442* of the Diffie-Hellman key agreement, this would be the party's own443* Diffie-Hellman private key.444*445* @exception InvalidKeyException if the given key is446* inappropriate for this key agreement, e.g., is of the wrong type or447* has an incompatible algorithm type.448*/449public final void init(Key key) throws InvalidKeyException {450init(key, JCAUtil.getDefSecureRandom());451}452453/**454* Initializes this key agreement with the given key and source of455* randomness. The given key is required to contain all the algorithm456* parameters required for this key agreement.457*458* <p> If the key agreement algorithm requires random bytes, it gets them459* from the given source of randomness, {@code random}.460* However, if the underlying461* algorithm implementation does not require any random bytes,462* {@code random} is ignored.463*464* @param key the party's private information. For example, in the case465* of the Diffie-Hellman key agreement, this would be the party's own466* Diffie-Hellman private key.467* @param random the source of randomness468*469* @exception InvalidKeyException if the given key is470* inappropriate for this key agreement, e.g., is of the wrong type or471* has an incompatible algorithm type.472*/473public final void init(Key key, SecureRandom random)474throws InvalidKeyException {475if (spi != null) {476spi.engineInit(key, random);477} else {478try {479chooseProvider(I_NO_PARAMS, key, null, random);480} catch (InvalidAlgorithmParameterException e) {481// should never occur482throw new InvalidKeyException(e);483}484}485486if (!skipDebug && pdebug != null) {487pdebug.println("KeyAgreement." + algorithm + " algorithm from: " +488getProviderName());489}490}491492/**493* Initializes this key agreement with the given key and set of494* algorithm parameters.495*496* <p> If this key agreement requires any random bytes, it will get497* them using the498* {@link java.security.SecureRandom}499* implementation of the highest-priority500* installed provider as the source of randomness.501* (If none of the installed providers supply an implementation of502* SecureRandom, a system-provided source of randomness will be used.)503*504* @param key the party's private information. For example, in the case505* of the Diffie-Hellman key agreement, this would be the party's own506* Diffie-Hellman private key.507* @param params the key agreement parameters508*509* @exception InvalidKeyException if the given key is510* inappropriate for this key agreement, e.g., is of the wrong type or511* has an incompatible algorithm type.512* @exception InvalidAlgorithmParameterException if the given parameters513* are inappropriate for this key agreement.514*/515public final void init(Key key, AlgorithmParameterSpec params)516throws InvalidKeyException, InvalidAlgorithmParameterException517{518init(key, params, JCAUtil.getDefSecureRandom());519}520521private String getProviderName() {522return (provider == null) ? "(no provider)" : provider.getName();523}524525/**526* Initializes this key agreement with the given key, set of527* algorithm parameters, and source of randomness.528*529* @param key the party's private information. For example, in the case530* of the Diffie-Hellman key agreement, this would be the party's own531* Diffie-Hellman private key.532* @param params the key agreement parameters533* @param random the source of randomness534*535* @exception InvalidKeyException if the given key is536* inappropriate for this key agreement, e.g., is of the wrong type or537* has an incompatible algorithm type.538* @exception InvalidAlgorithmParameterException if the given parameters539* are inappropriate for this key agreement.540*/541public final void init(Key key, AlgorithmParameterSpec params,542SecureRandom random)543throws InvalidKeyException, InvalidAlgorithmParameterException544{545if (spi != null) {546spi.engineInit(key, params, random);547} else {548chooseProvider(I_PARAMS, key, params, random);549}550551if (!skipDebug && pdebug != null) {552pdebug.println("KeyAgreement." + algorithm + " algorithm from: " +553getProviderName());554}555}556557/**558* Executes the next phase of this key agreement with the given559* key that was received from one of the other parties involved in this key560* agreement.561*562* @param key the key for this phase. For example, in the case of563* Diffie-Hellman between 2 parties, this would be the other party's564* Diffie-Hellman public key.565* @param lastPhase flag which indicates whether or not this is the last566* phase of this key agreement.567*568* @return the (intermediate) key resulting from this phase, or null569* if this phase does not yield a key570*571* @exception InvalidKeyException if the given key is inappropriate for572* this phase.573* @exception IllegalStateException if this key agreement has not been574* initialized.575*/576public final Key doPhase(Key key, boolean lastPhase)577throws InvalidKeyException, IllegalStateException578{579chooseFirstProvider();580return spi.engineDoPhase(key, lastPhase);581}582583/**584* Generates the shared secret and returns it in a new buffer.585*586* <p>This method resets this {@code KeyAgreement} object to the state that587* it was in after the most recent call to one of the {@code init} methods.588* After a call to {@code generateSecret}, the object can be reused for589* further key agreement operations by calling {@code doPhase} to supply590* new keys, and then calling {@code generateSecret} to produce a new591* secret. In this case, the private information and algorithm parameters592* supplied to {@code init} will be used for multiple key agreement593* operations. The {@code init} method can be called after594* {@code generateSecret} to change the private information used in595* subsequent operations.596*597* @return the new buffer with the shared secret598*599* @exception IllegalStateException if this key agreement has not been600* initialized or if {@code doPhase} has not been called to supply the601* keys for all parties in the agreement602*/603public final byte[] generateSecret() throws IllegalStateException {604chooseFirstProvider();605return spi.engineGenerateSecret();606}607608/**609* Generates the shared secret, and places it into the buffer610* {@code sharedSecret}, beginning at {@code offset} inclusive.611*612* <p>If the {@code sharedSecret} buffer is too small to hold the613* result, a {@code ShortBufferException} is thrown.614* In this case, this call should be repeated with a larger output buffer.615*616* <p>This method resets this {@code KeyAgreement} object to the state that617* it was in after the most recent call to one of the {@code init} methods.618* After a call to {@code generateSecret}, the object can be reused for619* further key agreement operations by calling {@code doPhase} to supply620* new keys, and then calling {@code generateSecret} to produce a new621* secret. In this case, the private information and algorithm parameters622* supplied to {@code init} will be used for multiple key agreement623* operations. The {@code init} method can be called after624* {@code generateSecret} to change the private information used in625* subsequent operations.626*627* @param sharedSecret the buffer for the shared secret628* @param offset the offset in {@code sharedSecret} where the629* shared secret will be stored630*631* @return the number of bytes placed into {@code sharedSecret}632*633* @exception IllegalStateException if this key agreement has not been634* initialized or if {@code doPhase} has not been called to supply the635* keys for all parties in the agreement636* @exception ShortBufferException if the given output buffer is too small637* to hold the secret638*/639public final int generateSecret(byte[] sharedSecret, int offset)640throws IllegalStateException, ShortBufferException641{642chooseFirstProvider();643return spi.engineGenerateSecret(sharedSecret, offset);644}645646/**647* Creates the shared secret and returns it as a {@code SecretKey}648* object of the specified algorithm.649*650* <p>This method resets this {@code KeyAgreement} object to the state that651* it was in after the most recent call to one of the {@code init} methods.652* After a call to {@code generateSecret}, the object can be reused for653* further key agreement operations by calling {@code doPhase} to supply654* new keys, and then calling {@code generateSecret} to produce a new655* secret. In this case, the private information and algorithm parameters656* supplied to {@code init} will be used for multiple key agreement657* operations. The {@code init} method can be called after658* {@code generateSecret} to change the private information used in659* subsequent operations.660*661* @param algorithm the requested secret-key algorithm662*663* @return the shared secret key664*665* @exception IllegalStateException if this key agreement has not been666* initialized or if {@code doPhase} has not been called to supply the667* keys for all parties in the agreement668* @exception NoSuchAlgorithmException if the specified secret-key669* algorithm is not available670* @exception InvalidKeyException if the shared secret-key material cannot671* be used to generate a secret key of the specified algorithm (e.g.,672* the key material is too short)673*/674public final SecretKey generateSecret(String algorithm)675throws IllegalStateException, NoSuchAlgorithmException,676InvalidKeyException677{678chooseFirstProvider();679return spi.engineGenerateSecret(algorithm);680}681}682683684