1 /*
   2  * Copyright (c) 2003, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /*
  25  * @test
  26  * @bug 4856966
  27  * @summary Verify that the RSA KeyPairGenerator works (use -Dseed=X to set PRNG seed)
  28  * @author Andreas Sterbenz
  29  * @library ..
  30  * @library /test/lib
  31  * @modules jdk.crypto.cryptoki
  32  * @run main/othervm -Djava.security.debug=sunpkcs11 TestKeyPairGenerator
  33  * @run main/othervm -Djava.security.debug=sunpkcs11 TestKeyPairGenerator
  34  *                                                   sm TestKeyPairGenerator.policy
  35  * @key randomness
  36  */
  37 
  38 import java.math.BigInteger;
  39 import java.security.KeyPair;
  40 import java.security.KeyPairGenerator;
  41 import java.security.PrivateKey;
  42 import java.security.Provider;
  43 import java.security.PublicKey;
  44 import java.security.Signature;
  45 import java.security.interfaces.RSAPrivateCrtKey;
  46 import java.security.interfaces.RSAPublicKey;
  47 import java.security.spec.RSAKeyGenParameterSpec;
  48 import jdk.test.lib.RandomFactory;
  49 
  50 public class TestKeyPairGenerator extends PKCS11Test {
  51 
  52     private static Provider provider;
  53 
  54     private static byte[] data;
  55 
  56     private static void testSignature(String algorithm, PrivateKey privateKey,
  57             PublicKey publicKey) throws Exception {
  58         System.out.println("Testing " + algorithm + "...");
  59         Signature s = Signature.getInstance(algorithm, provider);
  60         s.initSign(privateKey);
  61         s.update(data);
  62         byte[] sig = s.sign();
  63         s.initVerify(publicKey);
  64         s.update(data);
  65         boolean result = s.verify(sig);
  66         if (result == false) {
  67             throw new Exception("Verification failed");
  68         }
  69     }
  70 
  71     private static void test(PrivateKey privateKey, PublicKey publicKey) throws Exception {
  72         testSignature("MD2withRSA", privateKey, publicKey);
  73         testSignature("MD5withRSA", privateKey, publicKey);
  74         testSignature("SHA1withRSA", privateKey, publicKey);
  75         testSignature("SHA224withRSA", privateKey, publicKey);
  76         testSignature("SHA256withRSA", privateKey, publicKey);
  77         RSAPublicKey rsaKey = (RSAPublicKey)publicKey;
  78         if (rsaKey.getModulus().bitLength() > 512) {
  79             // for SHA384 and SHA512 the data is too long for 512 bit keys
  80             testSignature("SHA384withRSA", privateKey, publicKey);
  81             testSignature("SHA512withRSA", privateKey, publicKey);
  82         }
  83     }
  84 
  85     // regression test for 4865198
  86     private static void testInvalidSignature(KeyPair kp1, KeyPair kp2) throws Exception {
  87         System.out.println("Testing signature with incorrect key...");
  88         Signature sig = Signature.getInstance("MD5withRSA", provider);
  89         sig.initSign(kp1.getPrivate());
  90         byte[] data = new byte[100];
  91         sig.update(data);
  92         byte[] signature = sig.sign();
  93         sig.initVerify(kp1.getPublic());
  94         sig.update(data);
  95         if (sig.verify(signature) == false) {
  96             throw new Exception("verification failed");
  97         }
  98         sig.initVerify(kp2.getPublic());
  99         sig.update(data);
 100         // verify needs to return false and not throw an Exception
 101         if (sig.verify(signature)) {
 102             throw new Exception("verification unexpectedly succeeded");
 103         }
 104     }
 105 
 106     public static void main(String[] args) throws Exception {
 107         main(new TestKeyPairGenerator(), args);
 108     }
 109 
 110     @Override
 111     public void main(Provider p) throws Exception {
 112         long start = System.currentTimeMillis();
 113         provider = p;
 114         data = new byte[2048];
 115         // keypair generation is very slow, test only a few short keys
 116         int[] keyLengths = {512, 512, 1024};
 117         BigInteger[] pubExps = {null, RSAKeyGenParameterSpec.F4, null};
 118         KeyPair[] keyPairs = new KeyPair[3];
 119         RandomFactory.getRandom().nextBytes(data);
 120         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", provider);
 121         for (int i = 0; i < keyLengths.length; i++) {
 122             int len = keyLengths[i];
 123             BigInteger exp = pubExps[i];
 124             System.out.println("Generating " + len + " bit keypair...");
 125             if (exp == null) {
 126                 kpg.initialize(len);
 127             } else {
 128                 kpg.initialize(new RSAKeyGenParameterSpec(len, exp));
 129             }
 130             KeyPair kp = kpg.generateKeyPair();
 131             keyPairs[i] = kp;
 132             RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic();
 133             System.out.println(publicKey);
 134             RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey)kp.getPrivate();
 135             if (publicKey.getModulus().equals(privateKey.getModulus()) == false) {
 136                 throw new Exception("Moduli do not match");
 137             }
 138             if (publicKey.getPublicExponent().equals(privateKey.getPublicExponent()) == false) {
 139                 throw new Exception("Exponents do not match");
 140             }
 141             int keyLen = publicKey.getModulus().bitLength();
 142             if ((keyLen > len) || (keyLen < len - 1)) {
 143                 throw new Exception("Incorrect key length: " + keyLen);
 144             }
 145             if (exp != null) {
 146                 if (exp.equals(publicKey.getPublicExponent()) == false) {
 147                     throw new Exception("Incorrect exponent");
 148                 }
 149             }
 150             test(privateKey, publicKey);
 151         }
 152         testInvalidSignature(keyPairs[0], keyPairs[1]);
 153         testInvalidSignature(keyPairs[0], keyPairs[2]);
 154         long stop = System.currentTimeMillis();
 155         System.out.println("All tests passed (" + (stop - start) + " ms).");
 156     }
 157 }