Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

In this page you can find the example usage for java.security KeyStore getCertificate.

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:ee.ria.xroad.common.TestCertUtil.java

/**
 * Loads a certificate with the specified org name from a keystore.
 * @param keyStore keystore from which to load the certificate
 * @param orgName name of the certificate org
 * @return X509Certificate//  w ww .j  a  v a 2s . c o m
 */
public static X509Certificate getCert(KeyStore keyStore, String orgName) {
    try {
        X509Certificate cert = (X509Certificate) keyStore.getCertificate(orgName);
        if (cert == null) {
            throw new RuntimeException(
                    "Unable to get certificate for " + "name \"" + orgName + "\" from keystore");
        }

        return cert;
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Returns the certificate associated with the given alias ,store and
 * password./*from ww w .  j av  a 2s .c  om*/
 * 
 * @param store
 *            the storePath
 * @param alias
 *            the alias name
 * @param password
 *            the password
 * @return the certificate, or null if the given alias does not exist or
 *         does not contain a certificate.
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public static X509Certificate getCertificateFromStore(String store, String alias, String password)
        throws Exception {
    KeyStore ks = getKeyStore(new File(store).toURL(), password);
    X509Certificate c = (X509Certificate) ks.getCertificate(alias);
    return c;
}

From source file:org.wso2.carbon.identity.sso.saml.tomcat.agent.Util.java

/**
 * Get the X509CredentialImpl object for a particular tenant
 * @return X509CredentialImpl object containing the public certificate of that tenant
 * @throws SSOAgentException Error when creating X509CredentialImpl object
 *///from   www  .j a va  2s .  c o  m
public static X509CredentialImpl getX509CredentialImpl() throws SSOAgentException {

    X509CredentialImpl credentialImpl;
    String keyStoreFile = SSOConfigs.getTrustStore();
    String keyStorePassword = SSOConfigs.getTrustStorePassword();
    String alias = SSOConfigs.getIdPCertAlias();
    KeyStore keyStore = getKeyStore(keyStoreFile, keyStorePassword, "JKS");
    try {
        java.security.cert.X509Certificate cert = null;
        if (alias != null) {
            cert = (X509Certificate) keyStore.getCertificate(alias);
            if (cert == null) {
                throw new SSOAgentException(
                        "Cannot find a certificate with the alias " + alias + "in the trust store");
            }
        }
        credentialImpl = new X509CredentialImpl(cert);
    } catch (Exception e) {
        throw new SSOAgentException("Error instantiating an X509CredentialImpl object " + "for the public cert",
                e);
    }

    return credentialImpl;
}

From source file:com.pieframework.runtime.utils.CertificateUtils.java

public static X509Certificate getCertificate(File certificateFile, String pass, String certAlias) {
    X509Certificate certificate = null;

    try {// ww w.j ava 2s.  co m
        FileInputStream cert = new FileInputStream(certificateFile);
        KeyStore pfxStore = KeyStore.getInstance("pkcs12");
        pfxStore.load(cert, pass.toCharArray());
        if (StringUtils.empty(certAlias) && pfxStore.size() > 0) {
            certAlias = pfxStore.aliases().nextElement();
        }
        certificate = (X509Certificate) pfxStore.getCertificate(certAlias);
        cert.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return certificate;
}

From source file:org.wso2.carbon.identity.authenticator.saml2.sso.util.Util.java

/**
 * Get the X509CredentialImpl object for a particular tenant
 *
 * @param domainName domain name//w ww .java  2s  .c om
 * @return X509CredentialImpl object containing the public certificate of that tenant
 * @throws org.wso2.carbon.identity.authenticator.saml2.sso.SAML2SSOAuthenticatorException Error when creating X509CredentialImpl object
 */
public static X509CredentialImpl getX509CredentialImplForTenant(String domainName)
        throws SAML2SSOAuthenticatorException {

    int tenantID = MultitenantConstants.SUPER_TENANT_ID;
    RealmService realmService = SAML2SSOAuthBEDataHolder.getInstance().getRealmService();

    // get the tenantID
    if (!domainName.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
        try {
            tenantID = realmService.getTenantManager().getTenantId(domainName);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            String errorMsg = "Error getting the TenantID for the domain name";
            log.error(errorMsg, e);
            throw new SAML2SSOAuthenticatorException(errorMsg, e);
        }
    }

    KeyStoreManager keyStoreManager = null;
    // get an instance of the corresponding Key Store Manager instance
    keyStoreManager = KeyStoreManager.getInstance(tenantID);

    X509CredentialImpl credentialImpl = null;
    try {
        if (tenantID != MultitenantConstants.SUPER_TENANT_ID) {
            // for non zero tenants, load private key from their generated key store

            KeyStore keystore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(domainName));
            java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) keystore
                    .getCertificate(domainName);
            credentialImpl = new X509CredentialImpl(cert);
        } else { // for tenant zero, load the cert corresponding to given alias in authenticators.xml
            String alias = SAML2SSOAuthBEDataHolder.getInstance().getIdPCertAlias();
            java.security.cert.X509Certificate cert = null;
            if (alias != null) {
                cert = (X509Certificate) keyStoreManager.getPrimaryKeyStore().getCertificate(alias);
                if (cert == null) {
                    String errorMsg = "Cannot find a certificate with the alias " + alias
                            + " in the default key store. Please check the 'KeyAlias' property in"
                            + " the SSO configuration of the authenticators.xml";
                    log.error(errorMsg);
                    throw new SAML2SSOAuthenticatorException(errorMsg);
                }
            } else { // if the idpCertAlias is not given, use the default certificate.
                cert = keyStoreManager.getDefaultPrimaryCertificate();
            }
            credentialImpl = new X509CredentialImpl(cert);
        }
    } catch (Exception e) {
        String errorMsg = "Error instantiating an X509CredentialImpl object for the public cert.";
        log.error(errorMsg, e);
        throw new SAML2SSOAuthenticatorException(errorMsg, e);
    }
    return credentialImpl;
}

From source file:org.wso2.carbon.identity.relyingparty.saml.X509CredentialUtil.java

/**
 * Creates the X509Credential from the TrustStore certificate.
 */// w w w .  j  a  v a  2 s  .  c  o m
public static X509Credential loadCredentialFromTrustStore(String alias, KeyStore trustStore)
        throws RelyingPartyException {
    X509Credential credential = null;
    java.security.cert.X509Certificate cert = null;

    try {
        if (trustStore.containsAlias(alias)) {
            cert = (java.security.cert.X509Certificate) trustStore.getCertificate(alias);
            credential = new X509CredentialImpl(cert);
        }
    } catch (KeyStoreException e) {
        log.error("Error while loading credentials from trust store", e);
        throw new RelyingPartyException("Error while loading credentials from trust store", e);
    }
    return credential;
}

From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java

/**
 * For debuging only.  Prints out keystore certificate chain.
 *
 * @param keystore Keystore to print out.
 * @throws KeyStoreException If the keystore is broken.
 *///from www . j  a v a  2  s  .co m
public static void printTrustCerts(KeyStore keystore) throws KeyStoreException {
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        String message = "Trusted certificate '" + alias + "':";
        Certificate trustedcert = keystore.getCertificate(alias);
        if (trustedcert != null && trustedcert instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) trustedcert;
            message += "\n  Subject DN: " + cert.getSubjectDN();
            message += "\n  Signature Algorithm: " + cert.getSigAlgName();
            message += "\n  Valid from: " + cert.getNotBefore();
            message += "\n  Valid until: " + cert.getNotAfter();
            message += "\n  Issuer: " + cert.getIssuerDN();
        }
        log.info(message);
    }
}

From source file:org.roda.common.certification.OOXMLSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String fileFormat)/*from  w  w w  . ja va  2s.c om*/
        throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
        UnrecoverableKeyException, InvalidFormatException, XMLSignatureException, MarshalException {

    Path output = Files.createTempFile("signed", "." + fileFormat);
    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
    Files.copy(input, output, copyOptions);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(keystore);
    ks.load(is, password.toCharArray());

    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    X509Certificate x509 = (X509Certificate) ks.getCertificate(alias);

    SignatureConfig signatureConfig = new SignatureConfig();
    signatureConfig.setKey(pk);
    signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
    OPCPackage pkg = OPCPackage.open(output.toString(), PackageAccess.READ_WRITE);
    signatureConfig.setOpcPackage(pkg);

    SignatureInfo si = new SignatureInfo();
    si.setSignatureConfig(signatureConfig);
    si.confirmSignature();

    // boolean b = si.verifySignature();
    pkg.close();
    IOUtils.closeQuietly(is);

    return output;
}

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

private static void loadCA() throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException,
        CertificateException, IOException, UnrecoverableKeyException {
    KeyStore caKeyStore = securityFactory.createKeyStore("PKCS12");

    File file = new File("test/resources/testdata/keys/testCA.p12");

    FileInputStream input = new FileInputStream(file);

    caKeyStore.load(input, "test".toCharArray());

    rootCertificate = (X509Certificate) caKeyStore.getCertificate("root");
    caCertificate = (X509Certificate) caKeyStore.getCertificate("ca");
    caPrivateKey = (PrivateKey) caKeyStore.getKey("ca", null);

    assertNotNull(caCertificate);/*from  w  w  w. j a v  a2 s.  c  o  m*/
    assertNotNull(caPrivateKey);
}

From source file:org.roda.core.plugins.plugins.characterization.OOXMLSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String fileFormat) throws IOException, GeneralSecurityException, InvalidFormatException,
        XMLSignatureException, MarshalException {

    Path output = Files.createTempFile("signed", "." + fileFormat);
    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
    Files.copy(input, output, copyOptions);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    try (InputStream is = new FileInputStream(keystore)) {
        ks.load(is, password.toCharArray());

        PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
        X509Certificate x509 = (X509Certificate) ks.getCertificate(alias);

        SignatureConfig signatureConfig = new SignatureConfig();
        signatureConfig.setKey(pk);/*w w  w  . j  a  v a2s  .c o m*/
        signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));

        try (OPCPackage pkg = OPCPackage.open(output.toString(), PackageAccess.READ_WRITE)) {
            signatureConfig.setOpcPackage(pkg);

            SignatureInfo si = new SignatureInfo();
            si.setSignatureConfig(signatureConfig);
            si.confirmSignature();

            // boolean b = si.verifySignature();
        }
    }
    return output;
}