1 /*
   2  * Copyright (c) 2015, 2018, 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 import java.security.*;
  24 import java.security.interfaces.RSAPrivateKey;
  25 import java.security.interfaces.RSAPublicKey;
  26 import java.security.spec.*;
  27 import java.util.*;
  28 import java.util.stream.IntStream;
  29 import static javax.crypto.Cipher.PRIVATE_KEY;
  30 import static javax.crypto.Cipher.PUBLIC_KEY;
  31 
  32 import jdk.test.lib.SigTestUtil;
  33 import static jdk.test.lib.SigTestUtil.SignatureType;
  34 
  35 /**
  36  * @test
  37  * @bug 8044199 8146293
  38  * @summary Create a signature for RSA and get its signed data. re-initiate
  39  *          the signature with the public key. The signature can be verified
  40  *          by acquired signed data.
  41  * @library /test/lib
  42  * @build jdk.test.lib.SigTestUtil
  43  * @run main SignatureTest 512
  44  * @run main SignatureTest 768
  45  * @run main SignatureTest 1024
  46  * @run main SignatureTest 2048
  47  * @run main/timeout=240 SignatureTest 4096
  48  * @run main/timeout=240 SignatureTest 5120
  49  * @run main/timeout=480 SignatureTest 6144
  50  */
  51 public class SignatureTest {
  52     /**
  53      * ALGORITHM name, fixed as RSA.
  54      */
  55     private static final String KEYALG = "RSA";
  56 
  57     /**
  58      * JDK default RSA Provider.
  59      */
  60     private static final String PROVIDER = "SunRsaSign";
  61 
  62     /**
  63      * How much times signature updated.
  64      */
  65     private static final int UPDATE_TIMES_FIFTY = 50;
  66 
  67     /**
  68      * How much times signature initial updated.
  69      */
  70     private static final int UPDATE_TIMES_HUNDRED = 100;
  71 
  72     public static void main(String[] args) throws Exception {
  73         int keySize = Integer.parseInt(args[0]);
  74         Iterable<String> md_alg_pkcs15 =
  75             SigTestUtil.getDigestAlgorithms(SignatureType.RSA, keySize);
  76 
  77         Iterable<String> md_alg_pss =
  78             SigTestUtil.getDigestAlgorithms(SignatureType.RSASSA_PSS, keySize);
  79 
  80         byte[] data = new byte[100];
  81         IntStream.range(0, data.length).forEach(j -> {
  82             data[j] = (byte) j;
  83         });
  84 
  85         // create a key pair
  86         KeyPair kpair = generateKeys(KEYALG, keySize);
  87         Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());
  88         Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());
  89 
  90         test(SignatureType.RSA, md_alg_pkcs15, privs, pubs, data);
  91         test(SignatureType.RSASSA_PSS, md_alg_pss, privs, pubs, data);
  92     }
  93 
  94     private static void test(SignatureType type, Iterable<String> digestAlgs,
  95             Key[] privs, Key[] pubs, byte[] data) throws RuntimeException {
  96 
  97         // For signature algorithm, create and verify a signature
  98         Arrays.stream(privs).forEach(priv
  99                 -> Arrays.stream(pubs).forEach(pub
 100                 -> digestAlgs.forEach(digestAlg -> {
 101             try {
 102                 AlgorithmParameterSpec sigParams =
 103                     SigTestUtil.generateDefaultParameter(type, digestAlg);
 104                 String sigAlg = SigTestUtil.generateSigAlg(type, digestAlg);
 105                 checkSignature(data, (PublicKey) pub, (PrivateKey) priv,
 106                         sigAlg, sigParams);
 107             } catch (NoSuchAlgorithmException | InvalidKeyException |
 108                     SignatureException | NoSuchProviderException |
 109                     InvalidAlgorithmParameterException ex) {
 110                 throw new RuntimeException(ex);
 111             }
 112         }
 113         )));
 114     }
 115 
 116     private static KeyPair generateKeys(String keyalg, int size)
 117             throws NoSuchAlgorithmException {
 118         KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyalg);
 119         kpg.initialize(size);
 120         return kpg.generateKeyPair();
 121     }
 122 
 123     private static Key[] manipulateKey(int type, Key key)
 124             throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
 125         KeyFactory kf = KeyFactory.getInstance(KEYALG, PROVIDER);
 126 
 127         switch (type) {
 128             case PUBLIC_KEY:
 129                 try {
 130                     kf.getKeySpec(key, RSAPrivateKeySpec.class);
 131                     throw new RuntimeException("Expected InvalidKeySpecException "
 132                             + "not thrown");
 133                 } catch (InvalidKeySpecException expected) {
 134                 }
 135 
 136                 return new Key[]{
 137                     kf.generatePublic(kf.getKeySpec(key, RSAPublicKeySpec.class)),
 138                     kf.generatePublic(new X509EncodedKeySpec(key.getEncoded())),
 139                     kf.generatePublic(new RSAPublicKeySpec(
 140                     ((RSAPublicKey) key).getModulus(),
 141                     ((RSAPublicKey) key).getPublicExponent()))
 142                 };
 143             case PRIVATE_KEY:
 144                 try {
 145                     kf.getKeySpec(key, RSAPublicKeySpec.class);
 146                     throw new RuntimeException("Expected InvalidKeySpecException"
 147                             + " not thrown");
 148                 } catch (InvalidKeySpecException expected) {
 149                 }
 150                 return new Key[]{
 151                     kf.generatePrivate(kf.getKeySpec(key,
 152                     RSAPrivateKeySpec.class)),
 153                     kf.generatePrivate(new PKCS8EncodedKeySpec(
 154                     key.getEncoded())),
 155                     kf.generatePrivate(new RSAPrivateKeySpec(((RSAPrivateKey) key).getModulus(),
 156                     ((RSAPrivateKey) key).getPrivateExponent()))
 157                 };
 158         }
 159         throw new RuntimeException("We shouldn't reach here");
 160     }
 161 
 162     private static void checkSignature(byte[] data, PublicKey pub,
 163             PrivateKey priv, String sigAlg, AlgorithmParameterSpec sigParams)
 164             throws NoSuchAlgorithmException, InvalidKeyException,
 165             SignatureException, NoSuchProviderException,
 166             InvalidAlgorithmParameterException {
 167         System.out.println("Testing " + sigAlg);
 168         Signature sig = Signature.getInstance(sigAlg, PROVIDER);
 169         sig.setParameter(sigParams);
 170 
 171         sig.initSign(priv);
 172         for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) {
 173             sig.update(data);
 174         }
 175         byte[] signedData = sig.sign();
 176 
 177         // Make sure signature verifies with original data
 178         sig.setParameter(sigParams);
 179         sig.initVerify(pub);
 180         for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) {
 181             sig.update(data);
 182         }
 183         if (!sig.verify(signedData)) {
 184             throw new RuntimeException("Failed to verify " + sigAlg
 185                     + " signature");
 186         }
 187 
 188         // Make sure signature does NOT verify when the original data
 189         // has changed
 190         sig.initVerify(pub);
 191         for (int i = 0; i < UPDATE_TIMES_FIFTY; i++) {
 192             sig.update(data);
 193         }
 194 
 195         if (sig.verify(signedData)) {
 196             throw new RuntimeException("Failed to detect bad " + sigAlg
 197                     + " signature");
 198         }
 199     }
 200 }