Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/com/sun/crypto/provider/KeyAgreement/DHKeyAgreement2.java
38867 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.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @bug 714672826* @summary DHKeyAgreement227* @author Jan Luehe28* @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true DHKeyAgreement229*/3031import java.io.*;32import java.math.BigInteger;33import java.security.*;34import java.security.spec.*;35import java.security.interfaces.*;36import javax.crypto.*;37import javax.crypto.spec.*;38import javax.crypto.interfaces.*;39import com.sun.crypto.provider.SunJCE;4041import sun.misc.HexDumpEncoder;4243/**44* This test utility executes the Diffie-Hellman key agreement protocol45* between 2 parties: Alice and Bob.46*47* By default, preconfigured parameters (1024 bit prime modulus and base48* generator used by SKIP) are used.49* If this program is called with the "-gen" option, a new set of parameters50* are created.51*/5253public class DHKeyAgreement2 {5455private static final String SUNJCE = "SunJCE";56private DHKeyAgreement2() {}5758public static void main(String argv[]) throws Exception {59String mode = "USE_SKIP_DH_PARAMS";6061DHKeyAgreement2 keyAgree = new DHKeyAgreement2();6263if (argv.length > 1) {64keyAgree.usage();65throw new Exception("Wrong number of command options");66} else if (argv.length == 1) {67if (!(argv[0].equals("-gen"))) {68keyAgree.usage();69throw new Exception("Unrecognized flag: " + argv[0]);70}71mode = "GENERATE_DH_PARAMS";72}7374keyAgree.run(mode);75System.out.println("Test Passed");76}7778private void run(String mode) throws Exception {7980DHParameterSpec dhSkipParamSpec;8182if (mode.equals("GENERATE_DH_PARAMS")) {83// Some central authority creates new DH parameters84System.err.println("Creating Diffie-Hellman parameters ...");85AlgorithmParameterGenerator paramGen86= AlgorithmParameterGenerator.getInstance("DH", SUNJCE);87paramGen.init(512);88AlgorithmParameters params = paramGen.generateParameters();89dhSkipParamSpec = (DHParameterSpec)params.getParameterSpec90(DHParameterSpec.class);91} else {92// use some pre-generated, default DH parameters93System.err.println("Using SKIP Diffie-Hellman parameters");94dhSkipParamSpec = new DHParameterSpec(skip1024Modulus,95skip1024Base);96}9798/*99* Alice creates her own DH key pair, using the DH parameters from100* above101*/102System.err.println("ALICE: Generate DH keypair ...");103KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH", SUNJCE);104aliceKpairGen.initialize(dhSkipParamSpec);105KeyPair aliceKpair = aliceKpairGen.generateKeyPair();106System.out.println("Alice DH public key:\n" +107aliceKpair.getPublic().toString());108System.out.println("Alice DH private key:\n" +109aliceKpair.getPrivate().toString());110DHParameterSpec dhParamSpec =111((DHPublicKey)aliceKpair.getPublic()).getParams();112AlgorithmParameters algParams = AlgorithmParameters.getInstance("DH", SUNJCE);113algParams.init(dhParamSpec);114System.out.println("Alice DH parameters:\n"115+ algParams.toString());116117// Alice executes Phase1 of her version of the DH protocol118System.err.println("ALICE: Execute PHASE1 ...");119KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH", SUNJCE);120aliceKeyAgree.init(aliceKpair.getPrivate());121122// Alice encodes her public key, and sends it over to Bob.123byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();124125/*126* Let's turn over to Bob. Bob has received Alice's public key127* in encoded format.128* He instantiates a DH public key from the encoded key material.129*/130KeyFactory bobKeyFac = KeyFactory.getInstance("DH", SUNJCE);131X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec132(alicePubKeyEnc);133PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);134135/*136* Bob gets the DH parameters associated with Alice's public key.137* He must use the same parameters when he generates his own key138* pair.139*/140dhParamSpec = ((DHPublicKey)alicePubKey).getParams();141142// Bob creates his own DH key pair143System.err.println("BOB: Generate DH keypair ...");144KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH", SUNJCE);145bobKpairGen.initialize(dhParamSpec);146KeyPair bobKpair = bobKpairGen.generateKeyPair();147System.out.println("Bob DH public key:\n" +148bobKpair.getPublic().toString());149System.out.println("Bob DH private key:\n" +150bobKpair.getPrivate().toString());151152// Bob executes Phase1 of his version of the DH protocol153System.err.println("BOB: Execute PHASE1 ...");154KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH", SUNJCE);155bobKeyAgree.init(bobKpair.getPrivate());156157// Bob encodes his public key, and sends it over to Alice.158byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();159160/*161* Alice uses Bob's public key for Phase2 of her version of the DH162* protocol.163* Before she can do so, she has to instanticate a DH public key164* from Bob's encoded key material.165*/166KeyFactory aliceKeyFac = KeyFactory.getInstance("DH", SUNJCE);167x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);168PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);169System.err.println("ALICE: Execute PHASE2 ...");170aliceKeyAgree.doPhase(bobPubKey, true);171172/*173* Bob uses Alice's public key for Phase2 of his version of the DH174* protocol.175*/176System.err.println("BOB: Execute PHASE2 ...");177bobKeyAgree.doPhase(alicePubKey, true);178179/*180* At this stage, both Alice and Bob have completed the DH key181* agreement protocol.182* Each generates the (same) shared secret.183*/184byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();185int aliceLen = aliceSharedSecret.length;186187// check if alice's key agreement has been reset afterwards188try {189aliceKeyAgree.generateSecret();190throw new Exception("Error: alice's KeyAgreement not reset");191} catch (IllegalStateException e) {192System.out.println("EXPECTED: " + e.getMessage());193}194195byte[] bobSharedSecret = new byte[aliceLen];196int bobLen;197try {198// provide output buffer that is too short199bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1);200} catch (ShortBufferException e) {201System.out.println("EXPECTED: " + e.getMessage());202}203// retry w/ output buffer of required size204bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0);205206// check if bob's key agreement has been reset afterwards207try {208bobKeyAgree.generateSecret(bobSharedSecret, 0);209throw new Exception("Error: bob's KeyAgreement not reset");210} catch (IllegalStateException e) {211System.out.println("EXPECTED: " + e.getMessage());212}213214System.out.println("Alice secret: " + toHexString(aliceSharedSecret));215System.out.println("Bob secret: " + toHexString(bobSharedSecret));216217if (aliceLen != bobLen) {218throw new Exception("Shared secrets have different lengths");219}220for (int i=0; i<aliceLen; i++) {221if (aliceSharedSecret[i] != bobSharedSecret[i]) {222throw new Exception("Shared secrets differ");223}224}225System.err.println("Shared secrets are the same");226227// Now let's return the shared secret as a SecretKey object228// and use it for encryption229System.out.println("Return shared secret as SecretKey object ...");230bobKeyAgree.doPhase(alicePubKey, true);231SecretKey desKey = bobKeyAgree.generateSecret("DES");232233Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");234desCipher.init(Cipher.ENCRYPT_MODE, desKey);235236byte[] cleartext = "This is just an example".getBytes();237byte[] ciphertext = desCipher.doFinal(cleartext);238239desCipher.init(Cipher.DECRYPT_MODE, desKey);240byte[] cleartext1 = desCipher.doFinal(ciphertext);241242int clearLen = cleartext.length;243int clear1Len = cleartext1.length;244if (clearLen != clear1Len) {245throw new Exception("DIFFERENT");246}247for (int i=0; i < clear1Len; i++) {248if (cleartext[i] != cleartext1[i]) {249throw new Exception("DIFFERENT");250}251}252System.err.println("SAME");253}254255/*256* Converts a byte to hex digit and writes to the supplied buffer257*/258private void byte2hex(byte b, StringBuffer buf) {259char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',260'9', 'A', 'B', 'C', 'D', 'E', 'F' };261int high = ((b & 0xf0) >> 4);262int low = (b & 0x0f);263buf.append(hexChars[high]);264buf.append(hexChars[low]);265}266267/*268* Converts a byte array to hex string269*/270private String toHexString(byte[] block) {271StringBuffer buf = new StringBuffer();272273int len = block.length;274275for (int i = 0; i < len; i++) {276byte2hex(block[i], buf);277if (i < len-1) {278buf.append(":");279}280}281return buf.toString();282}283284/*285* Prints the usage of this test.286*/287private void usage() {288System.err.print("DHKeyAgreement usage: ");289System.err.println("[-gen]");290}291292// The 1024 bit Diffie-Hellman modulus values used by SKIP293private static final byte skip1024ModulusBytes[] = {294(byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,295(byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,296(byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,297(byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,298(byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,299(byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,300(byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,301(byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,302(byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,303(byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,304(byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,305(byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,306(byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,307(byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,308(byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,309(byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,310(byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,311(byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,312(byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,313(byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,314(byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,315(byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,316(byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,317(byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,318(byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,319(byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,320(byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,321(byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,322(byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,323(byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,324(byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,325(byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7326};327328// The SKIP 1024 bit modulus329private static final BigInteger skip1024Modulus330= new BigInteger(1, skip1024ModulusBytes);331332// The base used with the SKIP 1024 bit modulus333private static final BigInteger skip1024Base = BigInteger.valueOf(2);334}335336337