Path: blob/master/test/jdk/sun/security/rsa/SignatureTest.java
41149 views
/*1* Copyright (c) 2015, 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*/22import java.security.*;23import java.security.interfaces.RSAPrivateKey;24import java.security.interfaces.RSAPublicKey;25import java.security.spec.*;26import java.util.*;27import java.util.stream.IntStream;28import static javax.crypto.Cipher.PRIVATE_KEY;29import static javax.crypto.Cipher.PUBLIC_KEY;3031import jdk.test.lib.Asserts;32import jdk.test.lib.SigTestUtil;33import static jdk.test.lib.SigTestUtil.SignatureType;3435/**36* @test37* @bug 8044199 8146293 816349838* @summary Ensure keys created from KeyFactory::getKeySpec and from constructors39* are equal.40* Create a signature for RSA and get its signed data. re-initiate41* the signature with the public key. The signature can be verified42* by acquired signed data.43* @library /test/lib ../tools/keytool/fakegen44* @build jdk.test.lib.SigTestUtil45* @build java.base/sun.security.rsa.RSAKeyPairGenerator46* @run main SignatureTest 51247* @run main SignatureTest 76848* @run main SignatureTest 102449* @run main SignatureTest 204850* @run main/timeout=240 SignatureTest 409651* @run main/timeout=240 SignatureTest 512052* @run main/timeout=480 SignatureTest 614453*/54public class SignatureTest {55/**56* ALGORITHM name, fixed as RSA.57*/58private static final String KEYALG = "RSA";5960/**61* JDK default RSA Provider.62*/63private static final String PROVIDER = "SunRsaSign";6465/**66* How much times signature updated.67*/68private static final int UPDATE_TIMES_FIFTY = 50;6970/**71* How much times signature initial updated.72*/73private static final int UPDATE_TIMES_HUNDRED = 100;7475public static void main(String[] args) throws Exception {76int keySize = Integer.parseInt(args[0]);77Iterable<String> md_alg_pkcs15 =78SigTestUtil.getDigestAlgorithms(SignatureType.RSA, keySize);7980Iterable<String> md_alg_pss =81SigTestUtil.getDigestAlgorithms(SignatureType.RSASSA_PSS, keySize);8283byte[] data = new byte[100];84IntStream.range(0, data.length).forEach(j -> {85data[j] = (byte) j;86});8788// create a key pair89KeyPair kpair = generateKeys(KEYALG, keySize);90Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());91Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());9293test(SignatureType.RSA, md_alg_pkcs15, privs, pubs, data);94test(SignatureType.RSASSA_PSS, md_alg_pss, privs, pubs, data);95}9697private static void test(SignatureType type, Iterable<String> digestAlgs,98Key[] privs, Key[] pubs, byte[] data) throws RuntimeException {99100// For signature algorithm, create and verify a signature101Arrays.stream(privs).forEach(priv102-> Arrays.stream(pubs).forEach(pub103-> digestAlgs.forEach(digestAlg -> {104try {105AlgorithmParameterSpec sigParams =106SigTestUtil.generateDefaultParameter(type, digestAlg);107String sigAlg = SigTestUtil.generateSigAlg(type, digestAlg);108checkSignature(data, (PublicKey) pub, (PrivateKey) priv,109sigAlg, sigParams);110} catch (NoSuchAlgorithmException | InvalidKeyException |111SignatureException | NoSuchProviderException |112InvalidAlgorithmParameterException ex) {113throw new RuntimeException(ex);114}115}116)));117}118119private static KeyPair generateKeys(String keyalg, int size)120throws NoSuchAlgorithmException {121KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyalg);122kpg.initialize(size);123return kpg.generateKeyPair();124}125126private static Key[] manipulateKey(int type, Key key)127throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {128KeyFactory kf = KeyFactory.getInstance(KEYALG, PROVIDER);129130switch (type) {131case PUBLIC_KEY:132try {133kf.getKeySpec(key, RSAPrivateKeySpec.class);134throw new RuntimeException("Expected InvalidKeySpecException "135+ "not thrown");136} catch (InvalidKeySpecException expected) {137}138139RSAPublicKeySpec pubKeySpec1 = kf.getKeySpec(key, RSAPublicKeySpec.class);140RSAPublicKeySpec pubKeySpec2 = new RSAPublicKeySpec(141((RSAPublicKey) key).getModulus(),142((RSAPublicKey) key).getPublicExponent());143144Asserts.assertTrue(keySpecEquals(pubKeySpec1, pubKeySpec2),145"Both RSAPublicKeySpec should be equal");146147X509EncodedKeySpec x509KeySpec1 = kf.getKeySpec(key, X509EncodedKeySpec.class);148X509EncodedKeySpec x509KeySpec2 = new X509EncodedKeySpec(key.getEncoded());149150Asserts.assertTrue(encodedKeySpecEquals(x509KeySpec1, x509KeySpec2),151"Both X509EncodedKeySpec should be equal");152153return new Key[]{154key,155kf.generatePublic(pubKeySpec1),156kf.generatePublic(x509KeySpec1)157};158case PRIVATE_KEY:159try {160kf.getKeySpec(key, RSAPublicKeySpec.class);161throw new RuntimeException("Expected InvalidKeySpecException"162+ " not thrown");163} catch (InvalidKeySpecException expected) {164}165RSAPrivateKeySpec privKeySpec1 = kf.getKeySpec(key, RSAPrivateKeySpec.class);166RSAPrivateKeySpec privKeySpec2 = new RSAPrivateKeySpec(167((RSAPrivateKey) key).getModulus(),168((RSAPrivateKey) key).getPrivateExponent());169170Asserts.assertTrue(keySpecEquals(privKeySpec1, privKeySpec2),171"Both RSAPrivateKeySpec should be equal");172173PKCS8EncodedKeySpec pkcsKeySpec1 = kf.getKeySpec(key, PKCS8EncodedKeySpec.class);174PKCS8EncodedKeySpec pkcsKeySpec2 = new PKCS8EncodedKeySpec(key.getEncoded());175176Asserts.assertTrue(encodedKeySpecEquals(pkcsKeySpec1, pkcsKeySpec2),177"Both PKCS8EncodedKeySpec should be equal");178179return new Key[]{180key,181kf.generatePrivate(privKeySpec1),182kf.generatePrivate(pkcsKeySpec1)183};184}185throw new RuntimeException("We shouldn't reach here");186}187188private static void checkSignature(byte[] data, PublicKey pub,189PrivateKey priv, String sigAlg, AlgorithmParameterSpec sigParams)190throws NoSuchAlgorithmException, InvalidKeyException,191SignatureException, NoSuchProviderException,192InvalidAlgorithmParameterException {193System.out.println("Testing " + sigAlg);194Signature sig = Signature.getInstance(sigAlg, PROVIDER);195sig.setParameter(sigParams);196197sig.initSign(priv);198for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) {199sig.update(data);200}201byte[] signedData = sig.sign();202203// Make sure signature verifies with original data204sig.setParameter(sigParams);205sig.initVerify(pub);206for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) {207sig.update(data);208}209if (!sig.verify(signedData)) {210throw new RuntimeException("Failed to verify " + sigAlg211+ " signature");212}213214// Make sure signature does NOT verify when the original data215// has changed216sig.initVerify(pub);217for (int i = 0; i < UPDATE_TIMES_FIFTY; i++) {218sig.update(data);219}220221if (sig.verify(signedData)) {222throw new RuntimeException("Failed to detect bad " + sigAlg223+ " signature");224}225}226227private static boolean keySpecEquals(RSAPublicKeySpec spec1, RSAPublicKeySpec spec2) {228return spec1.getModulus().equals(spec2.getModulus())229&& spec1.getPublicExponent().equals(spec2.getPublicExponent())230&& Objects.equals(spec1.getParams(), spec2.getParams());231}232233private static boolean keySpecEquals(RSAPrivateKeySpec spec1, RSAPrivateKeySpec spec2) {234return spec1.getModulus().equals(spec2.getModulus())235&& spec1.getPrivateExponent().equals(spec2.getPrivateExponent())236&& Objects.equals(spec1.getParams(), spec2.getParams());237}238239private static boolean encodedKeySpecEquals(EncodedKeySpec spec1, EncodedKeySpec spec2) {240return Objects.equals(spec1.getAlgorithm(), spec2.getAlgorithm())241&& spec1.getFormat().equals(spec2.getFormat())242&& Arrays.equals(spec1.getEncoded(), spec2.getEncoded());243}244}245246247