1 /*
   2  * Copyright (c) 2015, 2016, 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.InvalidKeyException;
  24 import java.security.Key;
  25 import java.security.KeyFactory;
  26 import java.security.KeyPair;
  27 import java.security.KeyPairGenerator;
  28 import java.security.NoSuchAlgorithmException;
  29 import java.security.NoSuchProviderException;
  30 import java.security.PrivateKey;
  31 import java.security.PublicKey;
  32 import java.security.Signature;
  33 import java.security.SignatureException;
  34 import java.security.interfaces.RSAPrivateKey;
  35 import java.security.interfaces.RSAPublicKey;
  36 import java.security.spec.InvalidKeySpecException;
  37 import java.security.spec.PKCS8EncodedKeySpec;
  38 import java.security.spec.RSAPrivateKeySpec;
  39 import java.security.spec.RSAPublicKeySpec;
  40 import java.security.spec.X509EncodedKeySpec;
  41 import java.util.Arrays;
  42 import java.util.stream.IntStream;
  43 import static javax.crypto.Cipher.PRIVATE_KEY;
  44 import static javax.crypto.Cipher.PUBLIC_KEY;
  45 
  46 /**
  47  * @test
  48  * @bug 8044199
  49  * @summary Create a signature for RSA and get its signed data. re-initiate
  50  *          the signature with the public key. The signature can be verified
  51  *          by acquired signed data.
  52  * @run main SignatureTest 512
  53  * @run main SignatureTest 768
  54  * @run main SignatureTest 1024
  55  * @run main SignatureTest 2048
  56  * @run main/timeout=240 SignatureTest 4096
  57  * @run main/timeout=240 SignatureTest 5120
  58  * @run main/timeout=240 SignatureTest 6144
  59  */
  60 public class SignatureTest {
  61     /**
  62      * ALGORITHM name, fixed as RSA.
  63      */
  64     private static final String KEYALG = "RSA";
  65 
  66     /**
  67      * JDK default RSA Provider.
  68      */
  69     private static final String PROVIDER = "SunRsaSign";
  70 
  71     /**
  72      * How much times signature updated.
  73      */
  74     private static final int UPDATE_TIMES_FIFTY = 50;
  75 
  76     /**
  77      * How much times signature initial updated.
  78      */
  79     private static final int UPDATE_TIMES_HUNDRED = 100;
  80 
  81     /**
  82      * Signature algorithms to test
  83      */
  84     private static final String[] SIGN_ALG = {"MD2withRSA", "MD5withRSA",
  85         "SHA1withRSA", "SHA256withRSA"};
  86 
  87     public static void main(String[] args) throws Exception {
  88         int testSize = Integer.parseInt(args[0]);
  89 
  90         byte[] data = new byte[100];
  91         IntStream.range(0, data.length).forEach(j -> {
  92             data[j] = (byte) j;
  93         });
  94 
  95         // create a key pair
  96         KeyPair kpair = generateKeys(KEYALG, testSize);
  97         Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());
  98         Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());
  99         // For signature algorithm, create and verify a signature
 100 
 101         Arrays.stream(privs).forEach(priv
 102                 -> Arrays.stream(pubs).forEach(pub
 103                 -> Arrays.stream(SIGN_ALG).forEach(testAlg -> {
 104             try {
 105                 checkSignature(data, (PublicKey) pub, (PrivateKey) priv,
 106                         testAlg);
 107             } catch (NoSuchAlgorithmException | InvalidKeyException |
 108                     SignatureException | NoSuchProviderException ex) {
 109                 throw new RuntimeException(ex);
 110             }
 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) throws NoSuchAlgorithmException,
 164             InvalidKeyException, SignatureException, NoSuchProviderException {
 165         Signature sig = Signature.getInstance(sigalg, PROVIDER);
 166         sig.initSign(priv);
 167         for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) {
 168             sig.update(data);
 169         }
 170         byte[] signedData = sig.sign();
 171 
 172         // Make sure signature verifies with original data
 173         sig.initVerify(pub);
 174         for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) {
 175             sig.update(data);
 176         }
 177         if (!sig.verify(signedData)) {
 178             throw new RuntimeException("Failed to verify " + sigalg
 179                     + " signature");
 180         }
 181 
 182         // Make sure signature does NOT verify when the original data
 183         // has changed
 184         sig.initVerify(pub);
 185         for (int i = 0; i < UPDATE_TIMES_FIFTY; i++) {
 186             sig.update(data);
 187         }
 188 
 189         if (sig.verify(signedData)) {
 190             throw new RuntimeException("Failed to detect bad " + sigalg
 191                     + " signature");
 192         }
 193     }
 194 }