Path: blob/master/test/jdk/com/sun/crypto/provider/KeyAgreement/DHKeyAgreement2.java
41155 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.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 java.util.HexFormat;37import javax.crypto.*;38import javax.crypto.spec.*;39import javax.crypto.interfaces.*;4041/**42* This test utility executes the Diffie-Hellman key agreement protocol43* between 2 parties: Alice and Bob.44*45* By default, preconfigured parameters (1024 bit prime modulus and base46* generator used by SKIP) are used.47* If this program is called with the "-gen" option, a new set of parameters48* are created.49*/5051public class DHKeyAgreement2 {5253private static final String SUNJCE = "SunJCE";5455// Hex formatter to upper case with ":" delimiter56private static final HexFormat HEX_FORMATTER = HexFormat.ofDelimiter(":").withUpperCase();5758private DHKeyAgreement2() {}5960public static void main(String argv[]) throws Exception {61String mode = "USE_SKIP_DH_PARAMS";6263DHKeyAgreement2 keyAgree = new DHKeyAgreement2();6465if (argv.length > 1) {66keyAgree.usage();67throw new Exception("Wrong number of command options");68} else if (argv.length == 1) {69if (!(argv[0].equals("-gen"))) {70keyAgree.usage();71throw new Exception("Unrecognized flag: " + argv[0]);72}73mode = "GENERATE_DH_PARAMS";74}7576keyAgree.run(mode);77System.out.println("Test Passed");78}7980private void run(String mode) throws Exception {8182DHParameterSpec dhSkipParamSpec;8384if (mode.equals("GENERATE_DH_PARAMS")) {85// Some central authority creates new DH parameters86System.err.println("Creating Diffie-Hellman parameters ...");87AlgorithmParameterGenerator paramGen88= AlgorithmParameterGenerator.getInstance("DH", SUNJCE);89paramGen.init(512);90AlgorithmParameters params = paramGen.generateParameters();91dhSkipParamSpec = (DHParameterSpec)params.getParameterSpec92(DHParameterSpec.class);93} else {94// use some pre-generated, default DH parameters95System.err.println("Using SKIP Diffie-Hellman parameters");96dhSkipParamSpec = new DHParameterSpec(skip1024Modulus,97skip1024Base);98}99100/*101* Alice creates her own DH key pair, using the DH parameters from102* above103*/104System.err.println("ALICE: Generate DH keypair ...");105KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH", SUNJCE);106aliceKpairGen.initialize(dhSkipParamSpec);107KeyPair aliceKpair = aliceKpairGen.generateKeyPair();108System.out.println("Alice DH public key:\n" +109aliceKpair.getPublic().toString());110System.out.println("Alice DH private key:\n" +111aliceKpair.getPrivate().toString());112DHParameterSpec dhParamSpec =113((DHPublicKey)aliceKpair.getPublic()).getParams();114AlgorithmParameters algParams = AlgorithmParameters.getInstance("DH", SUNJCE);115algParams.init(dhParamSpec);116System.out.println("Alice DH parameters:\n"117+ algParams.toString());118119// Alice executes Phase1 of her version of the DH protocol120System.err.println("ALICE: Execute PHASE1 ...");121KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH", SUNJCE);122aliceKeyAgree.init(aliceKpair.getPrivate());123124// Alice encodes her public key, and sends it over to Bob.125byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();126127/*128* Let's turn over to Bob. Bob has received Alice's public key129* in encoded format.130* He instantiates a DH public key from the encoded key material.131*/132KeyFactory bobKeyFac = KeyFactory.getInstance("DH", SUNJCE);133X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec134(alicePubKeyEnc);135PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);136137/*138* Bob gets the DH parameters associated with Alice's public key.139* He must use the same parameters when he generates his own key140* pair.141*/142dhParamSpec = ((DHPublicKey)alicePubKey).getParams();143144// Bob creates his own DH key pair145System.err.println("BOB: Generate DH keypair ...");146KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH", SUNJCE);147bobKpairGen.initialize(dhParamSpec);148KeyPair bobKpair = bobKpairGen.generateKeyPair();149System.out.println("Bob DH public key:\n" +150bobKpair.getPublic().toString());151System.out.println("Bob DH private key:\n" +152bobKpair.getPrivate().toString());153154// Bob executes Phase1 of his version of the DH protocol155System.err.println("BOB: Execute PHASE1 ...");156KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH", SUNJCE);157bobKeyAgree.init(bobKpair.getPrivate());158159// Bob encodes his public key, and sends it over to Alice.160byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();161162/*163* Alice uses Bob's public key for Phase2 of her version of the DH164* protocol.165* Before she can do so, she has to instanticate a DH public key166* from Bob's encoded key material.167*/168KeyFactory aliceKeyFac = KeyFactory.getInstance("DH", SUNJCE);169x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);170PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);171System.err.println("ALICE: Execute PHASE2 ...");172aliceKeyAgree.doPhase(bobPubKey, true);173174/*175* Bob uses Alice's public key for Phase2 of his version of the DH176* protocol.177*/178System.err.println("BOB: Execute PHASE2 ...");179bobKeyAgree.doPhase(alicePubKey, true);180181/*182* At this stage, both Alice and Bob have completed the DH key183* agreement protocol.184* Each generates the (same) shared secret.185*/186byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();187int aliceLen = aliceSharedSecret.length;188189// check if alice's key agreement has been reset afterwards190try {191aliceKeyAgree.generateSecret();192throw new Exception("Error: alice's KeyAgreement not reset");193} catch (IllegalStateException e) {194System.out.println("EXPECTED: " + e.getMessage());195}196197byte[] bobSharedSecret = new byte[aliceLen];198int bobLen;199try {200// provide output buffer that is too short201bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1);202} catch (ShortBufferException e) {203System.out.println("EXPECTED: " + e.getMessage());204}205// retry w/ output buffer of required size206bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0);207208// check if bob's key agreement has been reset afterwards209try {210bobKeyAgree.generateSecret(bobSharedSecret, 0);211throw new Exception("Error: bob's KeyAgreement not reset");212} catch (IllegalStateException e) {213System.out.println("EXPECTED: " + e.getMessage());214}215216System.out.println("Alice secret: " + HEX_FORMATTER.formatHex(aliceSharedSecret));217System.out.println("Bob secret: " + HEX_FORMATTER.formatHex(bobSharedSecret));218219if (aliceLen != bobLen) {220throw new Exception("Shared secrets have different lengths");221}222for (int i=0; i<aliceLen; i++) {223if (aliceSharedSecret[i] != bobSharedSecret[i]) {224throw new Exception("Shared secrets differ");225}226}227System.err.println("Shared secrets are the same");228229// Now let's return the shared secret as a SecretKey object230// and use it for encryption231System.out.println("Return shared secret as SecretKey object ...");232bobKeyAgree.doPhase(alicePubKey, true);233SecretKey desKey = bobKeyAgree.generateSecret("DES");234235Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");236desCipher.init(Cipher.ENCRYPT_MODE, desKey);237238byte[] cleartext = "This is just an example".getBytes();239byte[] ciphertext = desCipher.doFinal(cleartext);240241desCipher.init(Cipher.DECRYPT_MODE, desKey);242byte[] cleartext1 = desCipher.doFinal(ciphertext);243244int clearLen = cleartext.length;245int clear1Len = cleartext1.length;246if (clearLen != clear1Len) {247throw new Exception("DIFFERENT");248}249for (int i=0; i < clear1Len; i++) {250if (cleartext[i] != cleartext1[i]) {251throw new Exception("DIFFERENT");252}253}254System.err.println("SAME");255}256257/*258* Converts a byte to hex digit and writes to the supplied buffer259*/260private void byte2hex(byte b, StringBuffer buf) {261char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',262'9', 'A', 'B', 'C', 'D', 'E', 'F' };263int high = ((b & 0xf0) >> 4);264int low = (b & 0x0f);265buf.append(hexChars[high]);266buf.append(hexChars[low]);267}268269/*270* Prints the usage of this test.271*/272private void usage() {273System.err.print("DHKeyAgreement usage: ");274System.err.println("[-gen]");275}276277// The 1024 bit Diffie-Hellman modulus values used by SKIP278private static final byte skip1024ModulusBytes[] = {279(byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,280(byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,281(byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,282(byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,283(byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,284(byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,285(byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,286(byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,287(byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,288(byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,289(byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,290(byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,291(byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,292(byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,293(byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,294(byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,295(byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,296(byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,297(byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,298(byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,299(byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,300(byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,301(byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,302(byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,303(byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,304(byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,305(byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,306(byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,307(byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,308(byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,309(byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,310(byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7311};312313// The SKIP 1024 bit modulus314private static final BigInteger skip1024Modulus315= new BigInteger(1, skip1024ModulusBytes);316317// The base used with the SKIP 1024 bit modulus318private static final BigInteger skip1024Base = BigInteger.valueOf(2);319}320321322