Java Code Examples for java.security.cert.Certificate#verify()

The following examples show how to use java.security.cert.Certificate#verify() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InvalidBitString.java    From TencentKona-8 with GNU General Public License v2.0 7 votes vote down vote up
private static boolean test(Certificate target, Certificate signer,
        String title, boolean expected) throws Exception {
    System.out.print("Checking " + title + ": expected: " +
            (expected ? "    verified" : "NOT verified"));
    boolean actual;
    try {
        PublicKey pubKey = signer.getPublicKey();
        target.verify(pubKey);
        actual = true;
    } catch (SignatureException se) {
        actual = false;
    }
    System.out.println(", actual: " +
            (actual ? "    verified" : "NOT verified"));
    return actual == expected;
}
 
Example 2
Source File: InvalidBitString.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean test(Certificate target, Certificate signer,
        String title, boolean expected) throws Exception {
    System.out.print("Checking " + title + ": expected: " +
            (expected ? "    verified" : "NOT verified"));
    boolean actual;
    try {
        PublicKey pubKey = signer.getPublicKey();
        target.verify(pubKey);
        actual = true;
    } catch (SignatureException se) {
        actual = false;
    }
    System.out.println(", actual: " +
            (actual ? "    verified" : "NOT verified"));
    return actual == expected;
}
 
Example 3
Source File: InvalidBitString.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean test(Certificate target, Certificate signer,
        String title, boolean expected) throws Exception {
    System.out.print("Checking " + title + ": expected: " +
            (expected ? "    verified" : "NOT verified"));
    boolean actual;
    try {
        PublicKey pubKey = signer.getPublicKey();
        target.verify(pubKey);
        actual = true;
    } catch (SignatureException se) {
        actual = false;
    }
    System.out.println(", actual: " +
            (actual ? "    verified" : "NOT verified"));
    return actual == expected;
}
 
Example 4
Source File: Main.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Locates a signer for a given certificate from a given keystore and
 * returns the signer's certificate.
 * @param cert the certificate whose signer is searched, not null
 * @param ks the keystore to search with, not null
 * @return <code>cert</code> itself if it's already inside <code>ks</code>,
 * or a certificate inside <code>ks</code> who signs <code>cert</code>,
 * or null otherwise.
 */
private static Certificate getTrustedSigner(Certificate cert, KeyStore ks)
        throws Exception {
    if (ks.getCertificateAlias(cert) != null) {
        return cert;
    }
    for (Enumeration<String> aliases = ks.aliases();
            aliases.hasMoreElements(); ) {
        String name = aliases.nextElement();
        Certificate trustedCert = ks.getCertificate(name);
        if (trustedCert != null) {
            try {
                cert.verify(trustedCert.getPublicKey());
                return trustedCert;
            } catch (Exception e) {
                // Not verified, skip to the next one
            }
        }
    }
    return null;
}
 
Example 5
Source File: InvalidBitString.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean test(Certificate target, Certificate signer,
        String title, boolean expected) throws Exception {
    System.out.print("Checking " + title + ": expected: " +
            (expected ? "    verified" : "NOT verified"));
    boolean actual;
    try {
        PublicKey pubKey = signer.getPublicKey();
        target.verify(pubKey);
        actual = true;
    } catch (SignatureException se) {
        actual = false;
    }
    System.out.println(", actual: " +
            (actual ? "    verified" : "NOT verified"));
    return actual == expected;
}
 
Example 6
Source File: Main.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Locates a signer for a given certificate from a given keystore and
 * returns the signer's certificate.
 * @param cert the certificate whose signer is searched, not null
 * @param ks the keystore to search with, not null
 * @return <code>cert</code> itself if it's already inside <code>ks</code>,
 * or a certificate inside <code>ks</code> who signs <code>cert</code>,
 * or null otherwise.
 */
private static Certificate getTrustedSigner(Certificate cert, KeyStore ks)
        throws Exception {
    if (ks.getCertificateAlias(cert) != null) {
        return cert;
    }
    for (Enumeration<String> aliases = ks.aliases();
            aliases.hasMoreElements(); ) {
        String name = aliases.nextElement();
        Certificate trustedCert = ks.getCertificate(name);
        if (trustedCert != null) {
            try {
                cert.verify(trustedCert.getPublicKey());
                return trustedCert;
            } catch (Exception e) {
                // Not verified, skip to the next one
            }
        }
    }
    return null;
}
 
Example 7
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Locates a signer for a given certificate from a given keystore and
 * returns the signer's certificate.
 * @param cert the certificate whose signer is searched, not null
 * @param ks the keystore to search with, not null
 * @return <code>cert</code> itself if it's already inside <code>ks</code>,
 * or a certificate inside <code>ks</code> who signs <code>cert</code>,
 * or null otherwise. A label is added.
 */
private static Pair<String,Certificate>
        getSigner(Certificate cert, KeyStore ks) throws Exception {
    if (ks.getCertificateAlias(cert) != null) {
        return new Pair<>("", cert);
    }
    for (Enumeration<String> aliases = ks.aliases();
            aliases.hasMoreElements(); ) {
        String name = aliases.nextElement();
        Certificate trustedCert = ks.getCertificate(name);
        if (trustedCert != null) {
            try {
                cert.verify(trustedCert.getPublicKey());
                return new Pair<>(name, trustedCert);
            } catch (Exception e) {
                // Not verified, skip to the next one
            }
        }
    }
    return null;
}
 
Example 8
Source File: Main.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Locates a signer for a given certificate from a given keystore and
 * returns the signer's certificate.
 * @param cert the certificate whose signer is searched, not null
 * @param ks the keystore to search with, not null
 * @return <code>cert</code> itself if it's already inside <code>ks</code>,
 * or a certificate inside <code>ks</code> who signs <code>cert</code>,
 * or null otherwise. A label is added.
 */
private static Pair<String,Certificate>
        getSigner(Certificate cert, KeyStore ks) throws Exception {
    if (ks.getCertificateAlias(cert) != null) {
        return new Pair<>("", cert);
    }
    for (Enumeration<String> aliases = ks.aliases();
            aliases.hasMoreElements(); ) {
        String name = aliases.nextElement();
        Certificate trustedCert = ks.getCertificate(name);
        if (trustedCert != null) {
            try {
                cert.verify(trustedCert.getPublicKey());
                return new Pair<>(name, trustedCert);
            } catch (Exception e) {
                // Not verified, skip to the next one
            }
        }
    }
    return null;
}
 
Example 9
Source File: Main.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Locates a signer for a given certificate from a given keystore and
 * returns the signer's certificate.
 * @param cert the certificate whose signer is searched, not null
 * @param ks the keystore to search with, not null
 * @return <code>cert</code> itself if it's already inside <code>ks</code>,
 * or a certificate inside <code>ks</code> who signs <code>cert</code>,
 * or null otherwise. A label is added.
 */
private static Pair<String,Certificate>
        getSigner(Certificate cert, KeyStore ks) throws Exception {
    if (ks.getCertificateAlias(cert) != null) {
        return new Pair<>("", cert);
    }
    for (Enumeration<String> aliases = ks.aliases();
            aliases.hasMoreElements(); ) {
        String name = aliases.nextElement();
        Certificate trustedCert = ks.getCertificate(name);
        if (trustedCert != null) {
            try {
                cert.verify(trustedCert.getPublicKey());
                return new Pair<>(name, trustedCert);
            } catch (Exception e) {
                // Not verified, skip to the next one
            }
        }
    }
    return null;
}
 
Example 10
Source File: InvalidBitString.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static boolean test(Certificate target, Certificate signer,
        String title, boolean expected) throws Exception {
    System.out.print("Checking " + title + ": expected: " +
            (expected ? "    verified" : "NOT verified"));
    boolean actual;
    try {
        PublicKey pubKey = signer.getPublicKey();
        target.verify(pubKey);
        actual = true;
    } catch (SignatureException se) {
        actual = false;
    }
    System.out.println(", actual: " +
            (actual ? "    verified" : "NOT verified"));
    return actual == expected;
}
 
Example 11
Source File: InvalidBitString.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean test(Certificate target, Certificate signer,
        String title, boolean expected) throws Exception {
    System.out.print("Checking " + title + ": expected: " +
            (expected ? "    verified" : "NOT verified"));
    boolean actual;
    try {
        PublicKey pubKey = signer.getPublicKey();
        target.verify(pubKey);
        actual = true;
    } catch (SignatureException se) {
        actual = false;
    }
    System.out.println(", actual: " +
            (actual ? "    verified" : "NOT verified"));
    return actual == expected;
}
 
Example 12
Source File: Main.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Locates a signer for a given certificate from a given keystore and
 * returns the signer's certificate.
 * @param cert the certificate whose signer is searched, not null
 * @param ks the keystore to search with, not null
 * @return <code>cert</code> itself if it's already inside <code>ks</code>,
 * or a certificate inside <code>ks</code> who signs <code>cert</code>,
 * or null otherwise.
 */
private static Certificate getTrustedSigner(Certificate cert, KeyStore ks)
        throws Exception {
    if (ks.getCertificateAlias(cert) != null) {
        return cert;
    }
    for (Enumeration<String> aliases = ks.aliases();
            aliases.hasMoreElements(); ) {
        String name = aliases.nextElement();
        Certificate trustedCert = ks.getCertificate(name);
        if (trustedCert != null) {
            try {
                cert.verify(trustedCert.getPublicKey());
                return trustedCert;
            } catch (Exception e) {
                // Not verified, skip to the next one
            }
        }
    }
    return null;
}
 
Example 13
Source File: InvalidBitString.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static boolean test(Certificate target, Certificate signer,
        String title, boolean expected) throws Exception {
    System.out.print("Checking " + title + ": expected: " +
            (expected ? "    verified" : "NOT verified"));
    boolean actual;
    try {
        PublicKey pubKey = signer.getPublicKey();
        target.verify(pubKey);
        actual = true;
    } catch (SignatureException se) {
        actual = false;
    }
    System.out.println(", actual: " +
            (actual ? "    verified" : "NOT verified"));
    return actual == expected;
}
 
Example 14
Source File: CertHelper.java    From moVirt with Apache License 2.0 5 votes vote down vote up
public static boolean isCA(Certificate certificate) {
    try {
        certificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example 15
Source File: ZipVerifyUtil.java    From VirtualAPK with Apache License 2.0 5 votes vote down vote up
public static boolean verifyZip(String zipPath, Certificate remoteCertificate) {
    try {
        String certPath = checkZipFileForCertificate(zipPath);
        Certificate certificate = getCertificateFromZip(zipPath, certPath);
        remoteCertificate.verify(certificate.getPublicKey());
        return true;
    } catch (Exception e) {
        Log.w(Constants.TAG, e);
        return false;
    }
}
 
Example 16
Source File: KeystoreFactoryTest.java    From spring-boot-security-saml with MIT License 5 votes vote down vote up
@Test
public void loadCert() throws Exception {
    KeystoreFactory keystoreFactory = new KeystoreFactory(new DefaultResourceLoader());
    Certificate cert = keystoreFactory.loadCert("classpath:/localhost.cert");
    assertThat(cert.getType()).isEqualTo("X.509");
    cert.verify(cert.getPublicKey());
}
 
Example 17
Source File: KeystoreFactoryTest.java    From spring-boot-security-saml with MIT License 5 votes vote down vote up
@Test
public void loadKeystore() throws Exception {
    KeystoreFactory keystoreFactory = new KeystoreFactory(new DefaultResourceLoader());
    KeyStore keyStore = keystoreFactory.loadKeystore("classpath:/localhost.cert", "classpath:/localhost.key.der", "alias", "password");
    assertThat(keyStore.containsAlias("alias")).isTrue();
    assertThat(keyStore.size()).isEqualTo(1);
    Certificate cert = keyStore.getCertificate("alias");
    assertThat(cert.getType()).isEqualTo("X.509");
    cert.verify(cert.getPublicKey());
    Key key = keyStore.getKey("alias", "password".toCharArray());
    assertThat(key.getAlgorithm()).isEqualTo("RSA");
    assertThat(key.getFormat()).isEqualTo("PKCS#8");
}
 
Example 18
Source File: OpenSslCertManagerTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private void testGenerateSelfSignedCert(File key, File cert, File trustStore, String trustStorePassword, Subject sbj) throws Exception {
    ssl.generateSelfSignedCert(key, cert, sbj, 365);
    ssl.addCertToTrustStore(cert, "ca", trustStore, trustStorePassword);

    Certificate c = certFactory.generateCertificate(new FileInputStream(cert));

    c.verify(c.getPublicKey());

    // subject verification if provided
    if (sbj != null) {
        if (c instanceof X509Certificate) {
            X509Certificate x509Certificate = (X509Certificate) c;
            Principal p = x509Certificate.getSubjectDN();

            assertThat(String.format("CN=%s, O=%s", sbj.commonName(), sbj.organizationName()), is(p.getName()));

            if (sbj.subjectAltNames() != null && sbj.subjectAltNames().size() > 0) {
                final Collection<List<?>> sans = x509Certificate.getSubjectAlternativeNames();
                assertThat(sans, is(notNullValue()));
                assertThat(sbj.subjectAltNames().size(), is(sans.size()));
                for (final List<?> sanItem : sans) {
                    assertThat(sbj.subjectAltNames().containsValue(sanItem.get(1)), is(true));
                }
            }
        } else {
            fail();
        }
    }

    // truststore verification if provided
    if (trustStore != null) {
        KeyStore store = KeyStore.getInstance("PKCS12");
        store.load(new FileInputStream(trustStore), trustStorePassword.toCharArray());
        X509Certificate storeCert = (X509Certificate) store.getCertificate("ca");
        storeCert.verify(storeCert.getPublicKey());
    }
}
 
Example 19
Source File: SAML2SPKeystoreTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static Certificate createSelfSignedCert(final KeyPair keyPair) throws Exception {
    final X500Name dn = new X500Name("cn=Unknown");
    final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();

    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));

    final Date expiration = new Date(System.currentTimeMillis() + 100000);
    certGen.setEndDate(new Time(expiration));

    final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

    final TBSCertificate tbsCert = certGen.generateTBSCertificate();
    final ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));

    final Certificate cert = CertificateFactory.getInstance("X.509")
        .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    cert.verify(keyPair.getPublic());
    return cert;
}
 
Example 20
Source File: OpenSslCertManagerTest.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
private void testGenerateSignedCert(File caKey, File caCert, Subject caSbj, File key, File csr, File cert,
                                    File keyStore, String keyStorePassword, Subject sbj) throws Exception {

    ssl.generateSelfSignedCert(caKey, caCert, caSbj, 365);

    ssl.generateCsr(key, csr, sbj);

    ssl.generateCert(csr, caKey, caCert, cert, sbj, 365);

    ssl.addKeyAndCertToKeyStore(caKey, caCert, "ca", keyStore, keyStorePassword);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate c = cf.generateCertificate(new FileInputStream(cert));
    Certificate ca = cf.generateCertificate(new FileInputStream(caCert));

    c.verify(ca.getPublicKey());

    if (c instanceof X509Certificate) {
        X509Certificate x509Certificate = (X509Certificate) c;
        Principal p = x509Certificate.getSubjectDN();

        assertThat(String.format("CN=%s, O=%s", sbj.commonName(), sbj.organizationName()), is(p.getName()));

        if (sbj != null && sbj.subjectAltNames() != null && sbj.subjectAltNames().size() > 0) {
            final Collection<List<?>> snas = x509Certificate.getSubjectAlternativeNames();
            if (snas != null) {
                for (final List<?> sanItem : snas) {
                    assertThat(sbj.subjectAltNames().containsValue(sanItem.get(1)), is(true));
                }
            } else {
                fail();
            }
        }
    } else {
        fail();
    }

    // keystore verification if provided
    if (keyStore != null) {
        KeyStore store = KeyStore.getInstance("PKCS12");
        store.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());

        Key storeKey = store.getKey("ca", keyStorePassword.toCharArray());
        StringBuilder sb = new StringBuilder()
                .append("-----BEGIN PRIVATE KEY-----")
                .append(Base64.getEncoder().encodeToString(storeKey.getEncoded()))
                .append("-----END PRIVATE KEY-----");

        assertThat(sb.toString(), is(new String(Files.readAllBytes(caKey.toPath())).replace("\n", "")));

        X509Certificate storeCert = (X509Certificate) store.getCertificate("ca");
        storeCert.verify(storeCert.getPublicKey());
    }
}