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

The following examples show how to use java.security.cert.X509Certificate#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: ReadPKCS12.java    From openjdk-jdk9 with GNU General Public License v2.0 10 votes vote down vote up
private static void verifyCerts(Certificate[] certs) throws Exception {
    int n = certs.length;
    for (int i = 0; i < n - 1; i++) {
        X509Certificate cert = (X509Certificate)certs[i];
        X509Certificate issuer = (X509Certificate)certs[i + 1];
        if (cert.getIssuerX500Principal().equals(issuer.getSubjectX500Principal()) == false) {
            throw new Exception("Certificates do not chain");
        }
        cert.verify(issuer.getPublicKey());
        System.out.println("Verified: " + cert.getSubjectX500Principal());
    }
    X509Certificate last = (X509Certificate)certs[n - 1];
    // if self-signed, verify the final cert
    if (last.getIssuerX500Principal().equals(last.getSubjectX500Principal())) {
        last.verify(last.getPublicKey());
        System.out.println("Verified: " + last.getSubjectX500Principal());
    }
}
 
Example 2
Source File: CertService.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
 * 找到父证书所有的子证书,将子证书的father设为他自己
 * @param fatherCert
 */
public void setSonCert(X509Certificate fatherCert) throws CertificateEncodingException {
    log.debug("start setSonCert. Father FingerPrint:{}", NodeMgrTools.getCertFingerPrint(fatherCert.getEncoded()));
    List<X509Certificate> x509CertList = new ArrayList<>();
    String fatherType = CertTools.getCertType(fatherCert.getSubjectDN());
    if(CertTools.TYPE_CHAIN.equals(fatherType)){
        x509CertList = loadAllX509CertsByType(CertTools.TYPE_AGENCY);
    }else if(CertTools.TYPE_AGENCY.equals(fatherType)){
        x509CertList = loadAllX509CertsByType(CertTools.TYPE_NODE);
    }

    for(int i = 0; i < x509CertList.size(); i++) {
        X509Certificate temp = x509CertList.get(i);
        try{
            // 找子证书
            temp.verify(fatherCert.getPublicKey());
        }catch (Exception e) {
            // 签名不匹配则继续
            continue;
        }
        String sonFingerPrint = NodeMgrTools.getCertFingerPrint(temp.getEncoded());
        updateCertFather(sonFingerPrint, NodeMgrTools.getCertFingerPrint(fatherCert.getEncoded()));
        log.debug("end setSonCert. Father FingerPrint:{}, SonFingerPrint:{}",
                NodeMgrTools.getCertFingerPrint(fatherCert.getEncoded()), sonFingerPrint);
    }
}
 
Example 3
Source File: ForwardBuilder.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Verifies whether the input certificate completes the path.
 * Checks the cert against each trust anchor that was specified, in order,
 * and returns true as soon as it finds a valid anchor.
 * Returns true if the cert matches a trust anchor specified as a
 * certificate or if the cert verifies with a trust anchor that
 * was specified as a trusted {pubkey, caname} pair. Returns false if none
 * of the trust anchors are valid for this cert.
 *
 * @param cert the certificate to test
 * @return a boolean value indicating whether the cert completes the path.
 */
@Override
boolean isPathCompleted(X509Certificate cert) {
    for (TrustAnchor anchor : trustAnchors) {
        if (anchor.getTrustedCert() != null) {
            if (cert.equals(anchor.getTrustedCert())) {
                this.trustAnchor = anchor;
                return true;
            } else {
                continue;
            }
        }
        X500Principal principal = anchor.getCA();
        PublicKey publicKey = anchor.getCAPublicKey();

        if (principal != null && publicKey != null &&
                principal.equals(cert.getSubjectX500Principal())) {
            if (publicKey.equals(cert.getPublicKey())) {
                // the cert itself is a trust anchor
                this.trustAnchor = anchor;
                return true;
            }
            // else, it is a self-issued certificate of the anchor
        }

        // Check subject/issuer name chaining
        if (principal == null ||
                !principal.equals(cert.getIssuerX500Principal())) {
            continue;
        }

        // skip anchor if it contains a DSA key with no DSA params
        if (PKIX.isDSAPublicKeyWithoutParams(publicKey)) {
            continue;
        }

        /*
         * Check signature
         */
        try {
            cert.verify(publicKey, buildParams.sigProvider());
        } catch (InvalidKeyException ike) {
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() invalid "
                              + "DSA key found");
            }
            continue;
        } catch (GeneralSecurityException e){
            if (debug != null) {
                debug.println("ForwardBuilder.isPathCompleted() " +
                              "unexpected exception");
                e.printStackTrace();
            }
            continue;
        }

        this.trustAnchor = anchor;
        return true;
    }

    return false;
}
 
Example 4
Source File: AndroidSafetynetAttestation.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
private void validateCertificatePath(List<X509Certificate> certificates) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException {

    for (int i = 0; i < certificates.size(); i++) {
      X509Certificate subjectCert = certificates.get(i);
      X509Certificate issuerCert;

      if (i + 1 >= certificates.size()) {
        issuerCert = subjectCert;
      } else {
        issuerCert = certificates.get(i + 1);
      }

      // verify that the issuer matches the next one in the list
      if (!subjectCert.getIssuerX500Principal().equals(issuerCert.getSubjectX500Principal())) {
        throw new CertificateException("Failed to validate certificate path! Issuers dont match!");
      }

      // verify the certificate against the issuer
      subjectCert.verify(issuerCert.getPublicKey());
    }
  }
 
Example 5
Source File: ECSigParamsVerifyWithCert.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream is
            = new ByteArrayInputStream(ecEntityWithSigParamsStr.getBytes());
    X509Certificate ecEntityWithSigParams = (X509Certificate)certFactory.generateCertificate(is);
    is = new ByteArrayInputStream(ecSigner.getBytes());
    X509Certificate ecSigner = (X509Certificate)certFactory.generateCertificate(is);

    try {
        ecEntityWithSigParams.verify(ecSigner.getPublicKey());
        System.out.println("Test Passed: EC Cert verified");
    } catch (Exception e) {
        System.out.println("Failed, cannot verify EC certificate with sig params");
        throw e;
    }
}
 
Example 6
Source File: CertUtil.java    From littleca with Apache License 2.0 6 votes vote down vote up
/**
 * 验证用户证书签名合法性
 *
 * @param userCert
 * @param CAPublicKey
 * @return
 * @throws CertException
 */
public static boolean verifyUserCert(X509Certificate userCert, PublicKey CAPublicKey) throws CertException {
    try {
        if (userCert == null) {
            throw new CertException("userCert can't be null");
        }
        if (CAPublicKey == null) {
            throw new CertException("CAPublicKey can't be null");
        }
        userCert.verify(CAPublicKey);
        return true;
    } catch (Exception e) {
        System.err.println(e);
        return false;
    }
}
 
Example 7
Source File: PGPEncryptionUtilTest.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetX509CertificateFromPgpKeyPair() throws Exception
{

    Date today = new Date();
    PGPPublicKey pgpPublicKey = PGPEncryptionUtil.findPublicKeyById( findFile( PUBLIC_KEYRING ), PUBLIC_KEY_ID );
    PGPSecretKey pgpSecretKey = PGPEncryptionUtil.findSecretKeyById( findFile( SECRET_KEYRING ), SECRET_KEY_ID );
    X509Certificate x509Certificate = PGPEncryptionUtil
            .getX509CertificateFromPgpKeyPair( pgpPublicKey, pgpSecretKey, SECRET_PWD,
                    "C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc,"
                            + " OU=Certification Services Division,"
                            + " CN=Thawte Server CA/[email protected]",
                    "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala,"
                            + "OU=FreeSoft, CN=www.freesoft.org/[email protected]",

                    today, new Date( today.getTime() + ( 1000 * 60 * 60 * 24 ) ), new BigInteger( "1" ) );

    assertNotNull( x509Certificate );


    JcaPGPKeyConverter c = new JcaPGPKeyConverter();
    PublicKey publicKey = c.getPublicKey( pgpSecretKey.getPublicKey() );
    x509Certificate.verify( publicKey, new BouncyCastleProvider() );
}
 
Example 8
Source File: BouncyCastleSelfSignedCertGenerator.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
static String[] generate(String fqdn, KeyPair keypair, SecureRandom random, Date notBefore, Date notAfter)
        throws Exception {
    PrivateKey key = keypair.getPrivate();

    // Prepare the information required for generating an X.509 certificate.
    X500Name owner = new X500Name("CN=" + fqdn);
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            owner, new BigInteger(64, random), notBefore, notAfter, owner, keypair.getPublic());

    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(key);
    X509CertificateHolder certHolder = builder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
    cert.verify(keypair.getPublic());

    return newSelfSignedCertificate(fqdn, key, cert);
}
 
Example 9
Source File: CertService.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
 * 根据单个crt的内容,找父证书,
 * @param sonCert
 * @return String crt's address
 */
public String findFatherCert(X509Certificate sonCert) throws CertificateEncodingException {
    log.debug("start findFatherCert. son cert: {}", NodeMgrTools.getCertFingerPrint(sonCert.getEncoded()));
    List<X509Certificate> x509CertList = loadAllX509Certs();
    String result = "";
    for(int i = 0; i < x509CertList.size(); i++) {
        X509Certificate temp = x509CertList.get(i);
        try{
            sonCert.verify(temp.getPublicKey());
        }catch (Exception e) {
            // 签名不匹配则继续
            continue;
        }
        // 返回指纹
        result = NodeMgrTools.getCertFingerPrint(temp.getEncoded());
    }
    log.debug("end findFatherCert. find one FatherCert's finerPrint:{}", result);
    return result;
}
 
Example 10
Source File: XmppDomainVerifier.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
private boolean isSelfSigned(X509Certificate certificate) {
    try {
        certificate.verify(certificate.getPublicKey());
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 11
Source File: Main.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private boolean signedBy(X509Certificate end, X509Certificate ca) {
    if (!ca.getSubjectDN().equals(end.getIssuerDN())) {
        return false;
    }
    try {
        end.verify(ca.getPublicKey());
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 12
Source File: CertPathValidatorUtilities.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
protected static void verifyX509Certificate(X509Certificate cert, PublicKey publicKey,
                                            String sigProvider)
    throws GeneralSecurityException
{
    if (sigProvider == null)
    {
        cert.verify(publicKey);
    }
    else
    {
        cert.verify(publicKey, sigProvider);
    }
}
 
Example 13
Source File: Main.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Recursively tries to establish chain from pool of trusted certs.
 *
 * @param certToVerify the cert that needs to be verified.
 * @param chain the chain that's being built.
 * @param certs the pool of trusted certs
 *
 * @return true if successful, false otherwise.
 */
private boolean buildChain(X509Certificate certToVerify,
                    Vector<Certificate> chain,
                    Hashtable<Principal, Vector<Certificate>> certs) {
    Principal issuer = certToVerify.getIssuerDN();
    if (isSelfSigned(certToVerify)) {
        // reached self-signed root cert;
        // no verification needed because it's trusted.
        chain.addElement(certToVerify);
        return true;
    }

    // Get the issuer's certificate(s)
    Vector<Certificate> vec = certs.get(issuer);
    if (vec == null) {
        return false;
    }

    // Try out each certificate in the vector, until we find one
    // whose public key verifies the signature of the certificate
    // in question.
    for (Enumeration<Certificate> issuerCerts = vec.elements();
         issuerCerts.hasMoreElements(); ) {
        X509Certificate issuerCert
            = (X509Certificate)issuerCerts.nextElement();
        PublicKey issuerPubKey = issuerCert.getPublicKey();
        try {
            certToVerify.verify(issuerPubKey);
        } catch (Exception e) {
            continue;
        }
        if (buildChain(issuerCert, chain, certs)) {
            chain.addElement(certToVerify);
            return true;
        }
    }
    return false;
}
 
Example 14
Source File: AbstractRevocationStatusChecker.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isSelfSigned(X509Certificate cert) {
   try {
      cert.verify(cert.getPublicKey());
      return true;
   } catch (Exception var3) {
      return false;
   }
}
 
Example 15
Source File: AbstractRevocationStatusChecker.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isSelfSigned(X509Certificate cert) {
   try {
      cert.verify(cert.getPublicKey());
      return true;
   } catch (Exception var3) {
      return false;
   }
}
 
Example 16
Source File: CertPathValidatorUtilities.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
protected static void verifyX509Certificate(X509Certificate cert, PublicKey publicKey,
                                            String sigProvider)
    throws GeneralSecurityException
{
    if (sigProvider == null)
    {
        cert.verify(publicKey);
    }
    else
    {
        cert.verify(publicKey, sigProvider);
    }
}
 
Example 17
Source File: XmppDomainVerifier.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
private boolean isSelfSigned(X509Certificate certificate) {
    try {
        certificate.verify(certificate.getPublicKey());
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 18
Source File: CertificateHelper.java    From CapturePacket with MIT License 4 votes vote down vote up
public static KeyStore createServerCertificate(String commonName,
                                               SubjectAlternativeNameHolder subjectAlternativeNames,
                                               Authority authority, Certificate caCert, PrivateKey caPrivKey)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        IOException, OperatorCreationException, CertificateException,
        InvalidKeyException, SignatureException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);

    X500Name issuer = new X509CertificateHolder(caCert.getEncoded())
            .getSubject();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());

    X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
    name.addRDN(BCStyle.CN, commonName);
    name.addRDN(BCStyle.O, authority.certOrganisation());
    name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName());
    X500Name subject = name.build();

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE,
            new Date(System.currentTimeMillis() + ONE_DAY), subject, keyPair.getPublic());

    builder.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(keyPair.getPublic()));
    builder.addExtension(Extension.basicConstraints, false,
            new BasicConstraints(false));

    subjectAlternativeNames.fillInto(builder);

    X509Certificate cert = signCertificate(builder, caPrivKey);

    cert.checkValidity(new Date());
    cert.verify(caCert.getPublicKey());

    KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType()
    /* , PROVIDER_NAME */);
    result.load(null, null);
    Certificate[] chain = { cert, caCert };
    result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
            authority.password(), chain);

    return result;
}
 
Example 19
Source File: TlsUtils.java    From tessera with Apache License 2.0 4 votes vote down vote up
default void generateKeyStoreWithSelfSignedCertificate(String address, Path privateKeyFile, char[] password)
        throws NoSuchAlgorithmException, IOException, OperatorCreationException, CertificateException,
                InvalidKeyException, NoSuchProviderException, SignatureException, KeyStoreException {

    final SecureRandom secureRandom = new SecureRandom();

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ENCRYPTION);
    keyGen.initialize(2048, secureRandom);
    KeyPair keypair = keyGen.generateKeyPair();
    final PublicKey publicKey = keypair.getPublic();
    final PrivateKey privateKey = keypair.getPrivate();
    final String cnString = address.replaceFirst("^(http[s]?://www\\.|http[s]?://|www\\.)", "");
    final X500Name commonName = new X500Name(COMMON_NAME_STRING + cnString);
    Date startDate = new Date(System.currentTimeMillis());
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
    calendar.add(Calendar.YEAR, 1);
    Date endDate = calendar.getTime();

    X509v3CertificateBuilder builder =
            new JcaX509v3CertificateBuilder(
                    commonName, new BigInteger(64, secureRandom), startDate, endDate, commonName, publicKey);

    GeneralName[] subjectAlternativeNames =
            new GeneralName[] {
                new GeneralName(GeneralName.dNSName, LOCALHOST),
                new GeneralName(GeneralName.dNSName, HostnameUtil.create().getHostName()),
                new GeneralName(GeneralName.iPAddress, LOCALHOST_IP),
                new GeneralName(GeneralName.iPAddress, LOCALHOST_IP_2),
                new GeneralName(GeneralName.iPAddress, HostnameUtil.create().getHostIpAddress())
            };

    builder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(subjectAlternativeNames));

    ContentSigner contentSigner = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(privateKey);
    X509CertificateHolder certHolder = builder.build(contentSigner);
    X509Certificate certificate =
            new JcaX509CertificateConverter().setProvider(provider).getCertificate(certHolder);

    certificate.verify(publicKey);

    KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
    keyStore.load(null, null);
    keyStore.setKeyEntry("tessera", privateKey, password, new X509Certificate[] {certificate});

    try (OutputStream keyStoreFile = Files.newOutputStream(privateKeyFile)) {
        keyStore.store(keyStoreFile, password);
    }
}
 
Example 20
Source File: TrustedCertificateStore.java    From cwac-netsecurity with Apache License 2.0 4 votes vote down vote up
/**
     * This non-{@code KeyStoreSpi} public interface is used by {@code
     * TrustManagerImpl} to locate the CA certificate that signed the
     * provided {@code X509Certificate}.
     */
/*
    public X509Certificate findIssuer(final X509Certificate c) {
        // match on verified issuer of Certificate
        CertSelector selector = new CertSelector() {
            @Override
            public boolean match(X509Certificate ca) {
                try {
                    c.verify(ca.getPublicKey());
                    return true;
                } catch (Exception e) {
                    return false;
                }
            }
        };
        X500Principal issuer = c.getIssuerX500Principal();
        X509Certificate user = findCert(addedDir, issuer, selector, X509Certificate.class);
        if (user != null) {
            return user;
        }
        X509Certificate system = findCert(systemDir, issuer, selector, X509Certificate.class);
        if (system != null && !isDeletedSystemCertificate(system)) {
            return system;
        }
        return null;
    }
*/

    public Set<X509Certificate> findAllIssuers(final X509Certificate c) {
        Set<X509Certificate> issuers = null;
        CertSelector selector = new CertSelector() {
            @Override
            public boolean match(X509Certificate ca) {
                try {
                    c.verify(ca.getPublicKey());
                    return true;
                } catch (Exception e) {
                    return false;
                }
            }
        };
        X500Principal issuer = c.getIssuerX500Principal();
/*
        Set<X509Certificate> userAddedCerts = findCert(addedDir, issuer, selector, Set.class);
        if (userAddedCerts != null) {
            issuers = userAddedCerts;
        }
        selector = new CertSelector() {
            @Override
            public boolean match(X509Certificate ca) {
                try {
                    if (isDeletedSystemCertificate(ca)) {
                        return false;
                    }
                    c.verify(ca.getPublicKey());
                    return true;
                } catch (Exception e) {
                    return false;
                }
            }
        };
        Set<X509Certificate> systemCerts = findCert(systemDir, issuer, selector, Set.class);
        if (systemCerts != null) {
            if (issuers != null) {
                issuers.addAll(systemCerts);
            } else {
                issuers = systemCerts;
            }
        }
*/
        return (issuers != null) ? issuers : Collections.<X509Certificate>emptySet();
    }