1 /*
2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package com.sun.crypto.provider;
27 
28 import java.util.*;
29 import java.lang.*;
30 import java.math.BigInteger;
31 import java.security.AccessController;
32 import java.security.InvalidAlgorithmParameterException;
33 import java.security.InvalidKeyException;
34 import java.security.Key;
35 import java.security.NoSuchAlgorithmException;
36 import java.security.SecureRandom;
37 import java.security.PrivilegedAction;
38 import java.security.ProviderException;
39 import java.security.spec.AlgorithmParameterSpec;
40 import java.security.spec.InvalidKeySpecException;
41 import javax.crypto.KeyAgreementSpi;
42 import javax.crypto.ShortBufferException;
43 import javax.crypto.SecretKey;
44 import javax.crypto.spec.*;
45 
46 import sun.security.util.KeyUtil;
47 
48 /**
49  * This class implements the Diffie-Hellman key agreement protocol between
50  * any number of parties.
51  *
52  * @author Jan Luehe
53  *
54  */
55 
56 public final class DHKeyAgreement
57 extends KeyAgreementSpi {
58 
59     private boolean generateSecret = false;
60     private BigInteger init_p = null;
61     private BigInteger init_g = null;
62     private BigInteger x = BigInteger.ZERO; // the private value
63     private BigInteger y = BigInteger.ZERO;
64 
65     private static class AllowKDF {
66 
67         private static final boolean VALUE = getValue();
68 
getValue()69         private static boolean getValue() {
70             return AccessController.doPrivileged(
71                 (PrivilegedAction<Boolean>)
72                 () -> Boolean.getBoolean("jdk.crypto.KeyAgreement.legacyKDF"));
73         }
74     }
75 
76     /**
77      * Empty constructor
78      */
DHKeyAgreement()79     public DHKeyAgreement() {
80     }
81 
82     /**
83      * Initializes this key agreement with the given key and source of
84      * randomness. The given key is required to contain all the algorithm
85      * parameters required for this key agreement.
86      *
87      * <p> If the key agreement algorithm requires random bytes, it gets them
88      * from the given source of randomness, <code>random</code>.
89      * However, if the underlying
90      * 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 case
94      * of the Diffie-Hellman key agreement, this would be the party's own
95      * Diffie-Hellman private key.
96      * @param random the source of randomness
97      *
98      * @exception InvalidKeyException if the given key is
99      * inappropriate for this key agreement, e.g., is of the wrong type or
100      * has an incompatible algorithm type.
101      */
engineInit(Key key, SecureRandom random)102     protected void engineInit(Key key, SecureRandom random)
103         throws InvalidKeyException
104     {
105         try {
106             engineInit(key, null, random);
107         } catch (InvalidAlgorithmParameterException e) {
108             // never happens, because we did not pass any parameters
109         }
110     }
111 
112     /**
113      * Initializes this key agreement with the given key, set of
114      * algorithm parameters, and source of randomness.
115      *
116      * @param key the party's private information. For example, in the case
117      * of the Diffie-Hellman key agreement, this would be the party's own
118      * Diffie-Hellman private key.
119      * @param params the key agreement parameters
120      * @param random the source of randomness
121      *
122      * @exception InvalidKeyException if the given key is
123      * inappropriate for this key agreement, e.g., is of the wrong type or
124      * has an incompatible algorithm type.
125      * @exception InvalidAlgorithmParameterException if the given parameters
126      * are inappropriate for this key agreement.
127      */
engineInit(Key key, AlgorithmParameterSpec params, SecureRandom random)128     protected void engineInit(Key key, AlgorithmParameterSpec params,
129                               SecureRandom random)
130         throws InvalidKeyException, InvalidAlgorithmParameterException
131     {
132         // ignore "random" parameter, because our implementation does not
133         // require any source of randomness
134         generateSecret = false;
135         init_p = null;
136         init_g = null;
137 
138         if ((params != null) && !(params instanceof DHParameterSpec)) {
139             throw new InvalidAlgorithmParameterException
140                 ("Diffie-Hellman parameters expected");
141         }
142         if (!(key instanceof javax.crypto.interfaces.DHPrivateKey)) {
143             throw new InvalidKeyException("Diffie-Hellman private key "
144                                           + "expected");
145         }
146         javax.crypto.interfaces.DHPrivateKey dhPrivKey;
147         dhPrivKey = (javax.crypto.interfaces.DHPrivateKey)key;
148 
149         // check if private key parameters are compatible with
150         // initialized ones
151         if (params != null) {
152             init_p = ((DHParameterSpec)params).getP();
153             init_g = ((DHParameterSpec)params).getG();
154         }
155         BigInteger priv_p = dhPrivKey.getParams().getP();
156         BigInteger priv_g = dhPrivKey.getParams().getG();
157         if (init_p != null && priv_p != null && !(init_p.equals(priv_p))) {
158             throw new InvalidKeyException("Incompatible parameters");
159         }
160         if (init_g != null && priv_g != null && !(init_g.equals(priv_g))) {
161             throw new InvalidKeyException("Incompatible parameters");
162         }
163         if ((init_p == null && priv_p == null)
164             || (init_g == null && priv_g == null)) {
165             throw new InvalidKeyException("Missing parameters");
166         }
167         init_p = priv_p;
168         init_g = priv_g;
169 
170         // store the x value
171         this.x = dhPrivKey.getX();
172     }
173 
174     /**
175      * Executes the next phase of this key agreement with the given
176      * key that was received from one of the other parties involved in this key
177      * agreement.
178      *
179      * @param key the key for this phase. For example, in the case of
180      * Diffie-Hellman between 2 parties, this would be the other party's
181      * Diffie-Hellman public key.
182      * @param lastPhase flag which indicates whether or not this is the last
183      * phase of this key agreement.
184      *
185      * @return the (intermediate) key resulting from this phase, or null if
186      * this phase does not yield a key
187      *
188      * @exception InvalidKeyException if the given key is inappropriate for
189      * this phase.
190      * @exception IllegalStateException if this key agreement has not been
191      * initialized.
192      */
engineDoPhase(Key key, boolean lastPhase)193     protected Key engineDoPhase(Key key, boolean lastPhase)
194         throws InvalidKeyException, IllegalStateException
195     {
196         if (!(key instanceof javax.crypto.interfaces.DHPublicKey)) {
197             throw new InvalidKeyException("Diffie-Hellman public key "
198                                           + "expected");
199         }
200         javax.crypto.interfaces.DHPublicKey dhPubKey;
201         dhPubKey = (javax.crypto.interfaces.DHPublicKey)key;
202 
203         if (init_p == null || init_g == null) {
204             throw new IllegalStateException("Not initialized");
205         }
206 
207         // check if public key parameters are compatible with
208         // initialized ones
209         BigInteger pub_p = dhPubKey.getParams().getP();
210         BigInteger pub_g = dhPubKey.getParams().getG();
211         if (pub_p != null && !(init_p.equals(pub_p))) {
212             throw new InvalidKeyException("Incompatible parameters");
213         }
214         if (pub_g != null && !(init_g.equals(pub_g))) {
215             throw new InvalidKeyException("Incompatible parameters");
216         }
217 
218         // validate the Diffie-Hellman public key
219         KeyUtil.validate(dhPubKey);
220 
221         // store the y value
222         this.y = dhPubKey.getY();
223 
224         // we've received a public key (from one of the other parties),
225         // so we are ready to create the secret, which may be an
226         // intermediate secret, in which case we wrap it into a
227         // Diffie-Hellman public key object and return it.
228         generateSecret = true;
229         if (lastPhase == false) {
230             byte[] intermediate = engineGenerateSecret();
231             return new DHPublicKey(new BigInteger(1, intermediate),
232                                    init_p, init_g);
233         } else {
234             return null;
235         }
236     }
237 
238     /**
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 it
243      * can be reused for further key agreements. Unless this key agreement is
244      * reinitialized with one of the <code>engineInit</code> methods, the same
245      * private information and algorithm parameters will be used for
246      * subsequent key agreements.
247      *
248      * @return the new buffer with the shared secret
249      *
250      * @exception IllegalStateException if this key agreement has not been
251      * completed yet
252      */
engineGenerateSecret()253     protected byte[] engineGenerateSecret()
254         throws IllegalStateException
255     {
256         int expectedLen = (init_p.bitLength() + 7) >>> 3;
257         byte[] result = new byte[expectedLen];
258         try {
259             engineGenerateSecret(result, 0);
260         } catch (ShortBufferException sbe) {
261             // should never happen since length are identical
262         }
263         return result;
264     }
265 
266     /**
267      * Generates the shared secret, and places it into the buffer
268      * <code>sharedSecret</code>, beginning at <code>offset</code>.
269      *
270      * <p>If the <code>sharedSecret</code> buffer is too small to hold the
271      * 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 it
276      * can be reused for further key agreements. Unless this key agreement is
277      * reinitialized with one of the <code>engineInit</code> methods, the same
278      * private information and algorithm parameters will be used for
279      * subsequent key agreements.
280      *
281      * @param sharedSecret the buffer for the shared secret
282      * @param offset the offset in <code>sharedSecret</code> where the
283      * shared secret will be stored
284      *
285      * @return the number of bytes placed into <code>sharedSecret</code>
286      *
287      * @exception IllegalStateException if this key agreement has not been
288      * completed yet
289      * @exception ShortBufferException if the given output buffer is too small
290      * to hold the secret
291      */
engineGenerateSecret(byte[] sharedSecret, int offset)292     protected int engineGenerateSecret(byte[] sharedSecret, int offset)
293         throws IllegalStateException, ShortBufferException
294     {
295         if (generateSecret == false) {
296             throw new IllegalStateException
297                 ("Key agreement has not been completed yet");
298         }
299 
300         if (sharedSecret == null) {
301             throw new ShortBufferException
302                 ("No buffer provided for shared secret");
303         }
304 
305         BigInteger modulus = init_p;
306         int expectedLen = (modulus.bitLength() + 7) >>> 3;
307         if ((sharedSecret.length - offset) < expectedLen) {
308             throw new ShortBufferException
309                     ("Buffer too short for shared secret");
310         }
311 
312         // Reset the key agreement after checking for ShortBufferException
313         // above, so user can recover w/o losing internal state
314         generateSecret = false;
315 
316         /*
317          * NOTE: BigInteger.toByteArray() returns a byte array containing
318          * the two's-complement representation of this BigInteger with
319          * the most significant byte is in the zeroth element. This
320          * contains the minimum number of bytes required to represent
321          * this BigInteger, including at least one sign bit whose value
322          * is always 0.
323          *
324          * Keys are always positive, and the above sign bit isn't
325          * actually used when representing keys.  (i.e. key = new
326          * BigInteger(1, byteArray))  To obtain an array containing
327          * exactly expectedLen bytes of magnitude, we strip any extra
328          * leading 0's, or pad with 0's in case of a "short" secret.
329          */
330         byte[] secret = this.y.modPow(this.x, modulus).toByteArray();
331         if (secret.length == expectedLen) {
332             System.arraycopy(secret, 0, sharedSecret, offset,
333                              secret.length);
334         } else {
335             // Array too short, pad it w/ leading 0s
336             if (secret.length < expectedLen) {
337                 System.arraycopy(secret, 0, sharedSecret,
338                     offset + (expectedLen - secret.length),
339                     secret.length);
340             } else {
341                 // Array too long, check and trim off the excess
342                 if ((secret.length == (expectedLen+1)) && secret[0] == 0) {
343                     // ignore the leading sign byte
344                     System.arraycopy(secret, 1, sharedSecret, offset, expectedLen);
345                 } else {
346                     throw new ProviderException("Generated secret is out-of-range");
347                 }
348             }
349         }
350         return expectedLen;
351     }
352 
353     /**
354      * Creates the shared secret and returns it as a secret key object
355      * of the requested algorithm type.
356      *
357      * <p>This method resets this <code>KeyAgreementSpi</code> object,
358      * so that it
359      * can be reused for further key agreements. Unless this key agreement is
360      * reinitialized with one of the <code>engineInit</code> methods, the same
361      * private information and algorithm parameters will be used for
362      * subsequent key agreements.
363      *
364      * @param algorithm the requested secret key algorithm
365      *
366      * @return the shared secret key
367      *
368      * @exception IllegalStateException if this key agreement has not been
369      * completed yet
370      * @exception NoSuchAlgorithmException if the requested secret key
371      * algorithm is not available
372      * @exception InvalidKeyException if the shared secret key material cannot
373      * be used to generate a secret key of the requested algorithm type (e.g.,
374      * the key material is too short)
375      */
engineGenerateSecret(String algorithm)376     protected SecretKey engineGenerateSecret(String algorithm)
377         throws IllegalStateException, NoSuchAlgorithmException,
378             InvalidKeyException
379     {
380         if (algorithm == null) {
381             throw new NoSuchAlgorithmException("null algorithm");
382         }
383 
384         if (!algorithm.equalsIgnoreCase("TlsPremasterSecret") &&
385             !AllowKDF.VALUE) {
386 
387             throw new NoSuchAlgorithmException("Unsupported secret key "
388                                                + "algorithm: " + algorithm);
389         }
390 
391         byte[] secret = engineGenerateSecret();
392         if (algorithm.equalsIgnoreCase("DES")) {
393             // DES
394             return new DESKey(secret);
395         } else if (algorithm.equalsIgnoreCase("DESede")
396                    || algorithm.equalsIgnoreCase("TripleDES")) {
397             // Triple DES
398             return new DESedeKey(secret);
399         } else if (algorithm.equalsIgnoreCase("Blowfish")) {
400             // Blowfish
401             int keysize = secret.length;
402             if (keysize >= BlowfishConstants.BLOWFISH_MAX_KEYSIZE)
403                 keysize = BlowfishConstants.BLOWFISH_MAX_KEYSIZE;
404             SecretKeySpec skey = new SecretKeySpec(secret, 0, keysize,
405                                                    "Blowfish");
406             return skey;
407         } else if (algorithm.equalsIgnoreCase("AES")) {
408             // AES
409             int keysize = secret.length;
410             SecretKeySpec skey = null;
411             int idx = AESConstants.AES_KEYSIZES.length - 1;
412             while (skey == null && idx >= 0) {
413                 // Generate the strongest key using the shared secret
414                 // assuming the key sizes in AESConstants class are
415                 // in ascending order
416                 if (keysize >= AESConstants.AES_KEYSIZES[idx]) {
417                     keysize = AESConstants.AES_KEYSIZES[idx];
418                     skey = new SecretKeySpec(secret, 0, keysize, "AES");
419                 }
420                 idx--;
421             }
422             if (skey == null) {
423                 throw new InvalidKeyException("Key material is too short");
424             }
425             return skey;
426         } else if (algorithm.equals("TlsPremasterSecret")) {
427             // remove leading zero bytes per RFC 5246 Section 8.1.2
428             return new SecretKeySpec(
429                         KeyUtil.trimZeroes(secret), "TlsPremasterSecret");
430         } else {
431             throw new NoSuchAlgorithmException("Unsupported secret key "
432                                                + "algorithm: "+ algorithm);
433         }
434     }
435 }
436