1 /*
  2  * Copyright (c) 2018, 2020, 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.Arrays;
 28 import java.util.stream.IntStream;
 29 import static javax.crypto.Cipher.PRIVATE_KEY;
 30 import static javax.crypto.Cipher.PUBLIC_KEY;
 31 
 32 /**
 33  * @test
 34  * @bug 8146293 8238448
 35  * @summary Create a signature for RSASSA-PSS and get its signed data.
 36  *          re-initiate the signature with the public key. The signature
 37  *          can be verified by acquired signed data.
 38  * @run main SignatureTest2 768
 39  * @run main SignatureTest2 1024
 40  * @run main SignatureTest2 1025
 41  * @run main SignatureTest2 2048
 42  * @run main SignatureTest2 2049
 43  * @run main/timeout=240 SignatureTest2 4096
 44  */
 45 public class SignatureTest2 {
 46     /**
 47      * ALGORITHM name, fixed as RSA.
 48      */
 49     private static final String KEYALG = "RSASSA-PSS";
 50 
 51     /**
 52      * JDK default RSA Provider.
 53      */
 54     private static final String PROVIDER = "SunRsaSign";
 55 
 56     /**
 57      * How much times signature updated.
 58      */
 59     private static final int UPDATE_TIMES_TWO = 2;
 60 
 61     /**
 62      * How much times signature initial updated.
 63      */
 64     private static final int UPDATE_TIMES_TEN = 10;
 65 
 66     /**
 67      * Digest algorithms to test w/ RSASSA-PSS signature algorithms
 68      */
 69     private static final String[] DIGEST_ALG = {
 70         "SHA-1", "SHA-224", "SHA-256", "SHA-384",
 71         "SHA-512", "SHA-512/224", "SHA-512/256"
 72     };
 73 
 74     private static final String SIG_ALG = "RSASSA-PSS";
 75 
 76     private static PSSParameterSpec genPSSParameter(String digestAlgo,
 77         int digestLen, int keySize) {
 78         // pick a salt length based on the key length and digestAlgo
 79         int saltLength = keySize/8 - digestLen - 2;
 80         if (saltLength < 0) {
 81             System.out.println("keysize: " + keySize/8 + ", digestLen: " + digestLen);
 82             return null;
 83         }
 84         return new PSSParameterSpec(digestAlgo, "MGF1",
 85             new MGF1ParameterSpec(digestAlgo), saltLength, 1);
 86     }
 87 
 88     public static void main(String[] args) throws Exception {
 89         final int testSize = Integer.parseInt(args[0]);
 90 
 91         byte[] data = new byte[100];
 92         IntStream.range(0, data.length).forEach(j -> {
 93             data[j] = (byte) j;
 94         });
 95 
 96         // create a key pair
 97         KeyPair kpair = generateKeys(KEYALG, testSize);
 98         Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());
 99         Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());
100 
101         // For messsage digest algorithm, create and verify a RSASSA-PSS signature
102         Arrays.stream(privs).forEach(priv
103                 -> Arrays.stream(pubs).forEach(pub
104                 -> Arrays.stream(DIGEST_ALG).forEach(testAlg -> {
105             checkSignature(data, (PublicKey) pub, (PrivateKey) priv,
106                     testAlg, testSize);
107         }
108         )));
109 
110     }
111 
112     private static KeyPair generateKeys(String keyalg, int size)
113             throws NoSuchAlgorithmException {
114         KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyalg);
115         kpg.initialize(size);
116         return kpg.generateKeyPair();
117     }
118 
119     private static Key[] manipulateKey(int type, Key key)
120             throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
121         KeyFactory kf = KeyFactory.getInstance(KEYALG, PROVIDER);
122 
123         switch (type) {
124             case PUBLIC_KEY:
125                 return new Key[]{
126                     kf.generatePublic(kf.getKeySpec(key, RSAPublicKeySpec.class)),
127                     kf.generatePublic(new X509EncodedKeySpec(key.getEncoded())),
128                     kf.generatePublic(new RSAPublicKeySpec(
129                     ((RSAPublicKey) key).getModulus(),
130                     ((RSAPublicKey) key).getPublicExponent()))
131                 };
132             case PRIVATE_KEY:
133                 return new Key[]{
134                     kf.generatePrivate(kf.getKeySpec(key,
135                     RSAPrivateKeySpec.class)),
136                     kf.generatePrivate(new PKCS8EncodedKeySpec(
137                     key.getEncoded())),
138                     kf.generatePrivate(new RSAPrivateKeySpec(((RSAPrivateKey) key).getModulus(),
139                     ((RSAPrivateKey) key).getPrivateExponent()))
140                 };
141         }
142         throw new RuntimeException("We shouldn't reach here");
143     }
144 
145     private static void checkSignature(byte[] data, PublicKey pub,
146             PrivateKey priv, String digestAlg, int keySize) throws RuntimeException {
147         try {
148             Signature sig = Signature.getInstance(SIG_ALG, PROVIDER);
149             int digestLen = MessageDigest.getInstance(digestAlg).getDigestLength();
150             PSSParameterSpec params = genPSSParameter(digestAlg, digestLen, keySize);
151             if (params == null) {
152                 System.out.println("Skip test due to short key size");
153                 return;
154             }
155             sig.setParameter(params);
156             sig.initSign(priv);
157             for (int i = 0; i < UPDATE_TIMES_TEN; i++) {
158                 sig.update(data);
159             }
160             byte[] signedDataTen = sig.sign();
161 
162             // Make sure signature can be generated without re-init
163             sig.update(data);
164             byte[] signedDataOne = sig.sign();
165 
166             // Make sure signature verifies with original data
167             System.out.println("Verify using params " + sig.getParameters());
168             sig.initVerify(pub);
169             sig.setParameter(params);
170             for (int i = 0; i < UPDATE_TIMES_TEN; i++) {
171                 sig.update(data);
172             }
173             if (!sig.verify(signedDataTen)) {
174                 throw new RuntimeException("Signature verification test#1 failed w/ "
175                     + digestAlg);
176             }
177 
178             // Make sure signature can verify without re-init
179             sig.update(data);
180             if (!sig.verify(signedDataOne)) {
181                 throw new RuntimeException("Signature verification test#2 failed w/ "
182                     + digestAlg);
183             }
184 
185             // Make sure signature does NOT verify when the original data
186             // has changed
187             for (int i = 0; i < UPDATE_TIMES_TWO; i++) {
188                 sig.update(data);
189             }
190 
191             if (sig.verify(signedDataOne)) {
192                 throw new RuntimeException("Bad signature accepted w/ "
193                     + digestAlg);
194             }
195         } catch (NoSuchAlgorithmException | InvalidKeyException |
196                  SignatureException | NoSuchProviderException |
197                  InvalidAlgorithmParameterException e) {
198             e.printStackTrace();
199             throw new RuntimeException(e);
200         }
201     }
202 }