Example usage for java.security.cert X509Certificate getPublicKey

List of usage examples for java.security.cert X509Certificate getPublicKey

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getPublicKey.

Prototype

public abstract PublicKey getPublicKey();

Source Link

Document

Gets the public key from this certificate.

Usage

From source file:org.ejbca.extra.db.ExtRAMsgHelper.java

/**
 * Method used to verify signed data.//  ww w.  java  2  s  . c om
 * 
 * @param TrustedCACerts a Collection of trusted certificates, should contain the entire chains
 * @param TrustedCRLs a Collection of trusted CRLS, use null if no CRL check should be used.
 * @param signedData the data to verify
 * @param date the date used to check the validity against.
 * @return a ParsedSignatureResult.
 */
public static ParsedSignatureResult verifySignature(Collection cACertChain, Collection trustedCRLs,
        byte[] signedData, Date date) {
    boolean verifies = false;
    X509Certificate usercert = null;
    ParsedSignatureResult retval = new ParsedSignatureResult(false, null, null);
    byte[] content = null;

    try {
        // First verify the signature
        CMSSignedData sp = new CMSSignedData(signedData);

        CertStore certs = sp.getCertificatesAndCRLs("Collection", "BC");
        SignerInformationStore signers = sp.getSignerInfos();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ((CMSProcessableByteArray) sp.getSignedContent()).write(baos);
        content = baos.toByteArray();
        baos.close();

        Collection c = signers.getSigners();
        Iterator it = c.iterator();

        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());

            Iterator certIt = certCollection.iterator();
            usercert = (X509Certificate) certIt.next();

            boolean validalg = signer.getDigestAlgOID().equals(signAlg);

            verifies = validalg && signer.verify(usercert.getPublicKey(), "BC");

        }

        // Second validate the certificate           
        X509Certificate rootCert = null;
        Iterator iter = cACertChain.iterator();
        while (iter.hasNext()) {
            X509Certificate cert = (X509Certificate) iter.next();
            if (cert.getIssuerDN().equals(cert.getSubjectDN())) {
                rootCert = cert;
                break;
            }
        }

        if (rootCert == null) {
            throw new CertPathValidatorException("Error Root CA cert not found in cACertChain");
        }

        List list = new ArrayList();
        list.add(usercert);
        list.add(cACertChain);
        if (trustedCRLs != null) {
            list.add(trustedCRLs);
        }

        CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
        CertStore store = CertStore.getInstance("Collection", ccsp);

        //validating path
        List certchain = new ArrayList();
        certchain.addAll(cACertChain);
        certchain.add(usercert);
        CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain);

        Set trust = new HashSet();
        trust.add(new TrustAnchor(rootCert, null));

        CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);
        param.addCertStore(store);
        param.setDate(date);
        if (trustedCRLs == null) {
            param.setRevocationEnabled(false);
        } else {
            param.setRevocationEnabled(true);
        }
        cpv.validate(cp, param);
        retval = new ParsedSignatureResult(verifies, usercert, content);
    } catch (Exception e) {
        log.error("Error verifying data : ", e);
    }

    return retval;
}

From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java

/**
 * Tests request for a pkcs12/*from  ww  w . ja v  a 2  s  .  c o m*/
 * 
 * @throws Exception error
 */
@Test
public void test01RequestPKCS12() throws Exception {
    log.trace(">test01RequestPKCS12()");

    // find a CA (TestCA?) create a user
    // Send certificate request for a server generated PKCS12
    setupUser(SecConst.TOKEN_SOFT_P12);
    setupUserStatus(EndEntityConstants.STATUS_NEW);

    // POST the OCSP request
    URL url = new URL(httpReqPath + '/' + resourceReq);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    // we are going to do a POST
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    // POST it
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    OutputStream os = con.getOutputStream();
    os.write(("user=" + TEST_USERNAME + "&password=foo123&keylength=2048").getBytes("UTF-8"));
    os.close();
    assertEquals("Response code", 200, con.getResponseCode());
    // Some appserver (Weblogic) responds with
    // "application/x-pkcs12; charset=UTF-8"
    String contentType = con.getContentType();
    boolean contentTypeIsPkcs12 = contentType.startsWith("application/x-pkcs12");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // This works for small requests, and PKCS12 requests are small
    InputStream in = con.getInputStream();
    int b = in.read();
    while (b != -1) {
        baos.write(b);
        b = in.read();
    }
    baos.flush();
    in.close();
    byte[] respBytes = baos.toByteArray();
    assertTrue(respBytes.length > 0);
    if (!contentTypeIsPkcs12 && log.isDebugEnabled()) {
        // If the content-type isn't application/x-pkcs12 we like to know what we got back..
        log.debug(new String(respBytes));
    }
    assertTrue("contentType was " + contentType, contentTypeIsPkcs12);

    KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    ByteArrayInputStream is = new ByteArrayInputStream(respBytes);
    store.load(is, "foo123".toCharArray());
    assertTrue(store.containsAlias("ReqTest"));
    X509Certificate cert = (X509Certificate) store.getCertificate("ReqTest");
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pk;
        assertEquals(rsapk.getAlgorithm(), "RSA");
        assertEquals(2048, rsapk.getModulus().bitLength());
    } else {
        assertTrue("Public key is not RSA", false);
    }

    log.trace("<test01RequestPKCS12()");
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Generates a self signed certificate using the given properties.
 *
 * @param commonName the subject's common name
 * @param organization the subject's organization name
 * @param organizationUnit the subject's organization unit name
 * @param stateOrProvince the subject's state or province
 * @param country the subject's country code
 * @param locality the subject's locality
 * @param algorithm the algorithm to use
 * @param keySize the keysize to use/*w  w  w  . ja  va 2s  . c  o  m*/
 * @param signatureAlgorithm the signature algorithm to use
 * @param validFrom when the certificate is valid from
 * @param validTo when the certificate is valid until
 * @return The generated certificate
 * @throws Exception
 */
protected Pair<X509Certificate, PrivateKey> generateCertificate(String commonName, String organization,
        String organizationUnit, String stateOrProvince, String country, String locality, String algorithm,
        int keySize, String signatureAlgorithm, String validFrom, String validTo) throws Exception {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); // "RSA","BC"
    keyPairGenerator.initialize(keySize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    // Generate self-signed certificate
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.C, country);
    builder.addRDN(BCStyle.ST, stateOrProvince);
    builder.addRDN(BCStyle.L, locality);
    builder.addRDN(BCStyle.OU, organizationUnit);
    builder.addRDN(BCStyle.O, organization);
    builder.addRDN(BCStyle.CN, commonName);

    Date notBefore = null;
    Date notAfter = null;
    if (validFrom == null) {
        notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
    } else {
        DateTime notBeforeDateTime = DateUtil.getDateUtil().parseIfDate(validFrom);
        if (notBeforeDateTime == null) {
            throw new InternalServerErrorException("Invalid date format for 'validFrom' property");
        } else {
            notBefore = notBeforeDateTime.toDate();
        }
    }
    if (validTo == null) {
        Calendar date = Calendar.getInstance();
        date.setTime(new Date());
        date.add(Calendar.YEAR, 10);
        notAfter = date.getTime();
    } else {
        DateTime notAfterDateTime = DateUtil.getDateUtil().parseIfDate(validTo);
        if (notAfterDateTime == null) {
            throw new InternalServerErrorException("Invalid date format for 'validTo' property");
        } else {
            notAfter = notAfterDateTime.toDate();
        }
    }

    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());

    X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore,
            notAfter, builder.build(), keyPair.getPublic());

    ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC)
            .build(keyPair.getPrivate());

    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
            .getCertificate(v3CertGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());

    return Pair.of(cert, keyPair.getPrivate());
}

From source file:org.freebxml.omar.server.security.authentication.AuthenticationServiceImpl.java

private void loadPublicKeyToCertMap() throws RegistryException {
    try {//from www.j  a va 2  s .c o  m
        KeyStore store = getKeyStore();

        for (Enumeration e = store.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            X509Certificate cert = (X509Certificate) store.getCertificate(alias);
            PublicKey publicKey = cert.getPublicKey();
            publicKeyToCertMap.put(publicKey, cert);
        }
    } catch (KeyStoreException e) {
        throw new RegistryException(e);
    }

}

From source file:org.freebxml.omar.server.security.authentication.AuthenticationServiceImpl.java

protected void registerUserCertificate(String userId, X509Certificate cert) throws RegistryException {
    java.io.FileOutputStream fos = null;

    try {/* w w w . j a v a  2  s .c  o  m*/
        KeyStore keyStore = getKeyStore();

        //Make sure no other user is registered with same cert under a different alias
        String alias = getKeyStore().getCertificateAlias(cert);
        if ((null != alias) && (!userId.equalsIgnoreCase(alias))) {
            throw new UserRegistrationException(ServerResourceBundle.getInstance()
                    .getString("message.error.certificateAlreadyExists", new Object[] { userId, alias }));
        }

        // Check if already in store
        X509Certificate oldCert = null;

        try {
            oldCert = getCertificate(userId);
        } catch (Exception e) {
        }

        //System.err.println("Checking the certificates are the same...");
        if ((oldCert != null) && !certificatesAreSame(cert, oldCert)) {
            throw new UserRegistrationException(ServerResourceBundle.getInstance()
                    .getString("message.userRegistrationFailed", new Object[] { userId }));
        }

        //Add the cert. to the keystore if the cert. does not exist yet
        if (oldCert == null) {
            if (propsReader.getProperty("omar.security.validateCertificates").trim().equalsIgnoreCase("true")) {
                validateCertificate(cert);
            }

            synchronized (keyStoreWriteLock) {
                keyStore.setCertificateEntry(userId, cert);

                String keystoreFile = getKeyStoreFileName();
                fos = new java.io.FileOutputStream(keystoreFile);

                String keystorePass = getKeyStorePassword();
                keyStore.store(fos, keystorePass.toCharArray());
                fos.flush();
                fos.close();
                this.keyStore = null;

                //Update publicKeyToCertMap
                publicKeyToCertMap.put(cert.getPublicKey(), cert);
            }
        }
    } catch (KeyStoreException e) {
        throw new UserRegistrationException(e);
    } catch (IOException e) {
        throw new UserRegistrationException(e);
    } catch (java.security.cert.CertificateException e) {
        throw new UserRegistrationException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new UserRegistrationException(e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.glite.slcs.httpclient.ssl.ExtendedX509TrustManager.java

/**
 * Returns <code>true</code> iff the certificate issuer is in our trust
 * store and it have signed the cert./*from  ww  w  . j  a  v a2  s.co m*/
 * 
 * @param cert
 *            The X509 certificate to check.
 * @return <code>true</code> if the certificate issuer is in
 *         trustedIssuers list and have signed the cert.
 */
protected boolean isCertificateIssuerTrusted(X509Certificate cert) {
    //TODO: checks CA CRL
    // checks if an trusted issuer have signed the certificate
    boolean trusted = false;
    Iterator issuers = trustedIssuers_.iterator();
    while (issuers.hasNext()) {
        X509Certificate issuer = (X509Certificate) issuers.next();
        PublicKey issuerPublicKey = issuer.getPublicKey();
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("checking: " + issuer.getSubjectDN());
            }
            cert.verify(issuerPublicKey);
            trusted = true;
            break;
        } catch (GeneralSecurityException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(e);
            }
        }
    }

    if (!trusted) {
        LOG.warn("No trusted issuer found in TrustStore for: " + cert.getSubjectDN());
    }

    return trusted;
}

From source file:org.glite.slcs.pki.bouncycastle.Codec.java

/**
 * Stores the private key and certificate in a PKCS12 file. The certificate
 * Subject CN is used as key alias in the PKCS12 store.
 * //from  w  w  w  .  j ava2s .  c om
 * @param privateKey
 *            The private key.
 * @param certificate
 *            The X509 certificate.
 * @param chain
 *            The X509 certificate chain.
 * @param file
 *            The file object.
 * @param password
 *            The password for the PKCS12 file.
 * @throws GeneralSecurityException
 *             If a crypto error occurs.
 * @throws IOException
 *             If an IO error occurs.
 */
static public void storePKCS12(PrivateKey privateKey, X509Certificate certificate, X509Certificate chain[],
        File file, char[] password) throws GeneralSecurityException, IOException {
    // set the bag information for the PKCS12 keystore
    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privateKey;
    PublicKey publicKey = certificate.getPublicKey();
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifierStructure(publicKey));

    // the PKCS12 keystore key alias is the CN
    String alias = getPrincipalValue(certificate, X509Principal.CN);

    // build full cert chain
    int nCerts = chain.length + 1;
    Certificate certs[] = new Certificate[nCerts];
    certs[0] = certificate;
    for (int i = 0; i < chain.length; i++) {
        certs[i + 1] = chain[i];
    }
    // create a PKCS12 keystore
    KeyStore p12Store = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME);
    p12Store.load(null, null);
    // set the key entry
    p12Store.setKeyEntry(alias, privateKey, null, certs);
    // store the file
    FileOutputStream fos = new FileOutputStream(file);
    p12Store.store(fos, password);
    fos.close();
}

From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java

protected byte[] generateCertRequest(X509Certificate cert) throws GeneralSecurityException {

    int bits = ((RSAPublicKey) cert.getPublicKey()).getModulus().bitLength();

    this.keyPair = keyPairCache.getKeyPair(bits);

    return this.certFactory.createCertificateRequest(cert, this.keyPair);
}

From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java

protected void verifyDelegatedCert(X509Certificate certificate) throws GeneralSecurityException {
    RSAPublicKey pubKey = (RSAPublicKey) certificate.getPublicKey();
    RSAPrivateKey privKey = (RSAPrivateKey) this.keyPair.getPrivate();

    if (!pubKey.getModulus().equals(privKey.getModulus())) {
        throw new GeneralSecurityException(i18n.getMessage("keyMismatch"));
    }//from   w ww .  j  a  v a 2s  . c  o m
}

From source file:org.globus.gsi.trustmanager.TrustedCertPathFinder.java

private static X509Certificate checkCertificate(List<X509Certificate> trustedCertPath,
        X509Certificate x509Certificate, Certificate issuerCertificate) throws CertPathValidatorException {
    X509Certificate x509IssuerCertificate = (X509Certificate) issuerCertificate;

    // check that the next one is indeed issuer, normalizing to Globus DN format
    String issuerDN = CertificateUtil.toGlobusID(x509Certificate.getIssuerX500Principal());
    String issuerCertDN = CertificateUtil.toGlobusID(x509IssuerCertificate.getSubjectX500Principal());

    if (!(issuerDN.equals(issuerCertDN))) {
        throw new IllegalArgumentException("Incorrect certificate path, certificate in chain can only "
                + "be issuer of previous certificate");
    }/*w w w  .  jav  a  2  s.  c  o  m*/

    // validate integrity of signature
    PublicKey publicKey = x509IssuerCertificate.getPublicKey();
    try {
        x509Certificate.verify(publicKey);
    } catch (CertificateException e) {
        throw new CertPathValidatorException(
                "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertPathValidatorException(
                "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e);
    } catch (InvalidKeyException e) {
        throw new CertPathValidatorException(
                "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e);
    } catch (NoSuchProviderException e) {
        throw new CertPathValidatorException(
                "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e);
    } catch (SignatureException e) {
        throw new CertPathValidatorException(
                "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e);
    }

    trustedCertPath.add(x509Certificate);
    return x509IssuerCertificate;
}