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:gov.niem.ws.util.SecurityUtil.java

public static PublicKey getSignaturePublicKey(Document assertion)
        throws ParserConfigurationException, SAXException, IOException {
    Node keyInfoNode = null;/*from  w  w  w .j a va 2s  .  co  m*/
    try {
        keyInfoNode = (Node) signatureKeyInfoPath.evaluate(assertion, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    if (keyInfoNode == null) {
        return null;
    }

    X509Certificate signatureCert = getCertificateFromKeyInfo(keyInfoNode);
    if (signatureCert != null) {
        return signatureCert.getPublicKey();
    }

    return getPublicKeyFromKeyInfo(keyInfoNode);
}

From source file:Main.java

public static void checkValidityWithPublicKey(X509Certificate certificate, PublicKey publicKey)
        throws CertificateNotYetValidException, CertificateExpiredException {

    Date now = new Date();
    long nowTime = now.getTime();
    final int oneMinute = 60000;
    Date afterAddingOneMinute = new Date(nowTime + (5 * oneMinute));

    //we are checking the certificate against current time plus five minutes to prevent false failure because of sync problems
    certificate.checkValidity(afterAddingOneMinute);
    if (!certificate.getPublicKey().equals(publicKey)) {
        throw new RuntimeException("Failed to validate public key");
    }// w ww . j a va2  s . c o  m
}

From source file:mitm.common.security.certificate.X509CertificateInspector.java

/**
 * Generates a SubjectKeyIdentifier by calculating the SHA1 hash over encoded public key. Outlook 2010
 * uses this method to calculate the SubjectKeyIdentifier when the certificate does not have a 
 * SubjectKeyIdentifier./* w  w w  . j  a  v a  2s.co m*/
 * 
 * Note: this is not RFC compliant! and is a Microsoft invention.
 *  
 * See https://bugzilla.mozilla.org/show_bug.cgi?id=559243 and 
 * http://www.ietf.org/mail-archive/web/smime/current/msg18730.html for more information why this is needed for
 * messages sent by Outlook 2010
 */
public static byte[] calculateSubjectKeyIdentifierMicrosoft(X509Certificate certificate) throws IOException {
    try {
        return Digests.digest(certificate.getPublicKey().getEncoded(), Digest.SHA1);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (NoSuchProviderException e) {
        throw new IOException(e);
    }
}

From source file:ch.bfh.unicert.certimport.Main.java

/**
 * Create a certificate fot the given CSV record
 *
 * @param record the record to parse/*w ww  .jav  a  2  s. c o m*/
 * @throws InvalidNameException
 */
private static void createCertificate(CSVRecord record) throws InvalidNameException {

    int recordid = Integer.parseInt(record.get(0));
    String pemCert = record.get(1);
    String institution = record.get(2);
    int revoked = Integer.parseInt(record.get(3));
    if (revoked == 1) {
        System.out.println("Certficate " + recordid + " is revoked. Looking for next certificate...");
        return;
    }

    String studyBranch = record.get(5);
    String uniqueId = record.get(6);
    String mail = record.get(8);

    CertificateFactory cf;
    X509Certificate cert;
    try {
        cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(pemCert.getBytes()));
    } catch (CertificateException ex) {
        logger.log(Level.SEVERE, "Not able to read certificate for record {0}, exception: {1}",
                new Object[] { recordid, ex });
        return;
    }

    DSAPublicKey pubKey = (DSAPublicKey) cert.getPublicKey();

    String commonName = cert.getSubjectDN().getName();

    LdapName ln = new LdapName(cert.getSubjectX500Principal().toString());

    for (Rdn rdn : ln.getRdns()) {
        if (rdn.getType().equalsIgnoreCase("CN")) {
            commonName = (String) rdn.getValue();
            break;
        } else if (rdn.getType().equalsIgnoreCase("UID")) {
            uniqueId = (String) rdn.getValue();
            break;
        } else if (rdn.getType().equalsIgnoreCase("OU")) {
            studyBranch = (String) rdn.getValue();
            break;
        }
    }

    IdentityData idData = new IdentityData(commonName, uniqueId, institution, studyBranch, null, null, null,
            null, null, "SwitchAAI", null);

    try {
        Certificate certificate = issuer.createClientCertificate(idData, keystorePath, pubKey, 10, "UniVote",
                new String[] { "Voter" }, uniBoardWSDLurl, uniBoardUrl, section);
        counter++;
        System.out.println("Certificate published for " + recordid + ". Count " + counter + " of 6424");
    } catch (CertificateCreationException ex) {
        logger.log(Level.SEVERE, "Not able to create certificate for record {0}, exception: {1}",
                new Object[] { recordid, ex });
    }
}

From source file:mitm.common.security.certificate.X509CertificateInspector.java

/**
 * Generates a SubjectKeyIdentifier by calculating the SHA1 hash over the BIT STRING
 * from SubjectPublicKeyInfo as defined in RFC2459.
 * @throws NoSuchAlgorithmException /*  www  .  j a v a2  s .  c  o m*/
 */
public static SubjectKeyIdentifier calculateSubjectKeyIdentifier(X509Certificate certificate)
        throws NoSuchAlgorithmException {
    return new JcaX509ExtensionUtils().createSubjectKeyIdentifier(certificate.getPublicKey());
}

From source file:be.fedict.trust.crl.CrlTrustLinker.java

/**
 * Checks the integrity of the given X509 CRL.
 * // w w  w.j  a  v  a2 s.  c  o m
 * @param x509crl
 *            the X509 CRL to verify the integrity.
 * @param issuerCertificate
 *            the assumed issuer of the given X509 CRL.
 * @param validationDate
 *            the validate date.
 * @return <code>true</code> if integrity is OK, <code>false</code>
 *         otherwise.
 */
public static boolean checkCrlIntegrity(X509CRL x509crl, X509Certificate issuerCertificate,
        Date validationDate) {
    if (false == x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) {
        return false;
    }
    try {
        x509crl.verify(issuerCertificate.getPublicKey());
    } catch (Exception e) {
        return false;
    }
    Date thisUpdate = x509crl.getThisUpdate();
    LOG.debug("validation date: " + validationDate);
    LOG.debug("CRL this update: " + thisUpdate);
    if (thisUpdate.after(validationDate)) {
        LOG.warn("CRL too young");
        return false;
    }
    LOG.debug("CRL next update: " + x509crl.getNextUpdate());
    if (validationDate.after(x509crl.getNextUpdate())) {
        LOG.debug("CRL too old");
        return false;
    }

    // assert cRLSign KeyUsage bit
    if (null == issuerCertificate.getKeyUsage()) {
        LOG.debug("No KeyUsage extension for CRL issuing certificate");
        return false;
    }

    if (false == issuerCertificate.getKeyUsage()[6]) {
        LOG.debug("cRLSign bit not set for CRL issuing certificate");
        return false;
    }

    return true;
}

From source file:Main.java

private static boolean isKnownRoot(X509Certificate root) throws NoSuchAlgorithmException, KeyStoreException {
    assert Thread.holdsLock(sLock);

    // Could not find the system key store. Conservatively report false.
    if (sSystemKeyStore == null)
        return false;

    // Check the in-memory cache first; avoid decoding the anchor from disk
    // if it has been seen before.
    Pair<X500Principal, PublicKey> key = new Pair<X500Principal, PublicKey>(root.getSubjectX500Principal(),
            root.getPublicKey());

    if (sSystemTrustAnchorCache.contains(key))
        return true;

    // Note: It is not sufficient to call sSystemKeyStore.getCertificiateAlias. If the server
    // supplies a copy of a trust anchor, X509TrustManagerExtensions returns the server's
    // version rather than the system one. getCertificiateAlias will then fail to find an anchor
    // name. This is fixed upstream in https://android-review.googlesource.com/#/c/91605/
    ///*from   w  w w  . ja  va2 s .com*/
    // TODO(davidben): When the change trickles into an Android release, query sSystemKeyStore
    // directly.

    // System trust anchors are stored under a hash of the principal. In case of collisions,
    // a number is appended.
    String hash = hashPrincipal(root.getSubjectX500Principal());
    for (int i = 0; true; i++) {
        String alias = hash + '.' + i;
        if (!new File(sSystemCertificateDirectory, alias).exists())
            break;

        Certificate anchor = sSystemKeyStore.getCertificate("system:" + alias);
        // It is possible for this to return null if the user deleted a trust anchor. In
        // that case, the certificate remains in the system directory but is also added to
        // another file. Continue iterating as there may be further collisions after the
        // deleted anchor.
        if (anchor == null)
            continue;

        if (!(anchor instanceof X509Certificate)) {
            // This should never happen.
            String className = anchor.getClass().getName();
            Log.e(TAG, "Anchor " + alias + " not an X509Certificate: " + className);
            continue;
        }

        // If the subject and public key match, this is a system root.
        X509Certificate anchorX509 = (X509Certificate) anchor;
        if (root.getSubjectX500Principal().equals(anchorX509.getSubjectX500Principal())
                && root.getPublicKey().equals(anchorX509.getPublicKey())) {
            sSystemTrustAnchorCache.add(key);
            return true;
        }
    }

    return false;
}

From source file:net.sf.keystore_explorer.crypto.csr.pkcs10.Pkcs10Util.java

/**
 * Create a PKCS #10 certificate signing request (CSR) using the supplied
 * certificate, private key and signature algorithm.
 *
 * @param cert/*from w  w w .ja  v a2s .c o  m*/
 *            The certificate
 * @param privateKey
 *            The private key
 * @param signatureType
 *            Signature
 * @param challenge
 *            Challenge, optional, pass null if not required
 * @param unstructuredName
 *            An optional company name, pass null if not required
 * @param useExtensions
 *            Use extensions from cert for extensionRequest attribute?
 * @throws CryptoException
 *             If there was a problem generating the CSR
 * @return The CSR
 */
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey,
        SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions,
        Provider provider) throws CryptoException {

    try {
        JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(
                cert.getSubjectX500Principal(), cert.getPublicKey());

        // add challenge attribute
        if (challenge != null) {
            // PKCS#9 2.0: SHOULD use UTF8String encoding
            csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
        }

        if (unstructuredName != null) {
            csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
        }

        if (useExtensions) {
            // add extensionRequest attribute with all extensions from the certificate
            Certificate certificate = Certificate.getInstance(cert.getEncoded());
            Extensions extensions = certificate.getTBSCertificate().getExtensions();
            if (extensions != null) {
                csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
            }
        }

        // fall back to bouncy castle provider if given provider does not support the requested algorithm
        if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
            provider = new BouncyCastleProvider();
        }

        ContentSigner contentSigner = null;

        if (provider == null) {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
        } else {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider)
                    .build(privateKey);
        }

        PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);

        if (!verifyCsr(csr)) {
            throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
        }

        return csr;
    } catch (CertificateEncodingException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    } catch (OperatorCreationException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    }
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Fetch a public key (certificate) from PrivateKeyEntry object
 *
 * @param keyEntry a PrivateKeyEntry object containing key of interest
 * @return the PublicKey object containing the targeted public key
 *
 *///from   ww  w.  j a v a  2 s .  co m
public static PublicKey getPublicKey(PrivateKeyEntry keyEntry) {
    if (keyEntry != null) {
        X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
        return cert.getPublicKey();
    }
    return null;
}

From source file:com.vangent.hieos.services.sts.util.STSUtil.java

/**
 *
 * @param certificate//from   w  w  w .j  av a2s.co m
 * @param addCertificate
 * @param addPublicKey
 * @return
 * @throws STSException
 */
static public KeyInfo getKeyInfo(X509Certificate certificate, boolean addCertificate, boolean addPublicKey)
        throws STSException {
    // Place the Certificate (public portion) for the issuer in the KeyInfo response.
    KeyInfo keyInfo = (KeyInfo) STSUtil.createXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
    if (addPublicKey) {
        KeyInfoHelper.addPublicKey(keyInfo, certificate.getPublicKey());
    }
    try {
        if (addCertificate) {
            KeyInfoHelper.addCertificate(keyInfo, certificate);
        }
    } catch (CertificateEncodingException ex) {
        throw new STSException("Unable to encode certificate: " + ex.getMessage());
    }
    return keyInfo;
}