Example usage for java.security KeyStore getCertificateChain

List of usage examples for java.security KeyStore getCertificateChain

Introduction

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

Prototype

public final Certificate[] getCertificateChain(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate chain associated with the given alias.

Usage

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Get the certificate chain for the CA certificate
 * /*from ww w.ja  va2s . c  om*/
 * @param trustedKs
 * @return
 */
private Certificate[] getCaCertChain(KeyStore trustedKs) {
    Certificate[] caCertChain = null;
    String certAlias = config.getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_CERT_ALIAS);

    try {
        caCertChain = trustedKs.getCertificateChain(certAlias);
    } catch (KeyStoreException kse) {
        throw new AlfrescoRuntimeException(kse.getMessage());
    }

    return caCertChain;
}

From source file:org.wso2.identity.integration.test.oidc.OIDCAuthzCodeIdTokenValidationTestCase.java

private void initServiceProviderKeys() throws Exception {

    KeyStore keyStore = KeyStore.getInstance("JKS");
    String jksPath = TestConfigurationProvider.getResourceLocation("IS") + File.separator + "sp"
            + File.separator + "keystores" + File.separator + "sp1KeyStore.jks";
    String jksPassword = "wso2carbon";

    keyStore.load(new FileInputStream(jksPath), jksPassword.toCharArray());

    String alias = "wso2carbon";
    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
            new KeyStore.PasswordProtection(jksPassword.toCharArray()));
    spPrivateKey = (RSAPrivateKey) pkEntry.getPrivateKey();

    // Load certificate chain
    Certificate[] chain = keyStore.getCertificateChain(alias);
    spX509PublicCert = (X509Certificate) chain[0];
}

From source file:edu.byu.wso2.apim.extensions.JWTDecoder.java

private String getAliasForX509CertThumb(KeyStore keyStore, byte[] thumb, MessageContext synapseContext) {
    SynapseLog synLog = getLog(synapseContext);
    Certificate cert = null;//from   w w w.  j  a va 2 s . c  om
    MessageDigest sha = null;

    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        handleSigVerificationException(e, synapseContext);
    }
    try {
        for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate[] certs = keyStore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = keyStore.getCertificate(alias);
                if (cert == null) {
                    return null;
                }
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            sha.reset();
            try {
                sha.update(cert.getEncoded());
            } catch (CertificateEncodingException e1) {
                //throw new Exception("Error encoding certificate");
            }
            byte[] data = sha.digest();
            if (new String(thumb).equals(hexify(data))) {
                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.traceOrDebug("Found matching alias: " + alias);
                }
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        if (log.isErrorEnabled()) {
            log.error("Error getting alias from keystore", e);
        }
    }
    return null;
}

From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java

/**
 * This first looks into the primary keystore and then looks at the other trust stores
 *
 * @see org.apache.ws.security.components.crypto.Crypto#getCertificates(String)
 *//*from   w  w w  .j a va  2  s . c  om*/
public X509Certificate[] getCertificates(String alias) throws WSSecurityException {

    Certificate[] certs = new Certificate[0];
    Certificate cert = null;
    try {
        if (this.keystore != null) {
            // There's a chance that there can only be a set of trust stores
            certs = keystore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a
                // result.
                cert = keystore.getCertificate(alias);
            }
        }

        if (certs == null && cert == null && this.trustStores != null) {
            // Now look into the trust stores
            Iterator trustStoreIter = this.trustStores.iterator();
            while (trustStoreIter.hasNext()) {
                KeyStore store = (KeyStore) trustStoreIter.next();
                certs = store.getCertificateChain(alias);
                if (certs != null) {
                    break; // found the certs
                } else {
                    cert = store.getCertificate(alias);
                }
            }
        }

        if (certs == null && cert == null && this.cacerts != null) {
            // There's a chance that there can only be a set of ca store
            certs = cacerts.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a
                // result.
                cert = cacerts.getCertificate(alias);
            }
        }

        if (cert != null) {
            certs = new Certificate[] { cert };
        } else if (certs == null) {
            // At this pont we don't have certs or a cert
            return null;
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore");
    }

    X509Certificate[] x509certs = new X509Certificate[0];
    if (certs != null) {
        x509certs = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            x509certs[i] = (X509Certificate) certs[i];
        }
    }
    return x509certs;
}

From source file:org.jenkinsci.plugins.androidsigning.SignApksBuilder.java

@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
        @Nonnull TaskListener listener) throws InterruptedException, IOException {
    if (isIntermediateFailure(run)) {
        listener.getLogger()/*  w  w w . jav  a  2  s.  c o m*/
                .println("[SignApksBuilder] skipping Sign APKs step because a previous step failed");
        return;
    }

    if (getEntries() != null && !getEntries().isEmpty()) {
        List<SignApksBuilder> newModelBuilders = singleEntryBuildersFromEntriesOfBuilder(this);
        for (SignApksBuilder builder : newModelBuilders) {
            builder.perform(run, workspace, launcher, listener);
        }
        return;
    }

    EnvVars env;
    if (run instanceof AbstractBuild) {
        env = run.getEnvironment(listener);
        env.overrideAll(((AbstractBuild<?, ?>) run).getBuildVariables());
    } else {
        env = new EnvVars();
    }

    FilePath builderDir = workspace.child(BUILDER_DIR);
    String excludeBuilderDir = builderDir.getName() + "/**";
    ZipalignTool zipalign = new ZipalignTool(env, workspace, listener.getLogger(), androidHome, zipalignPath);
    Map<String, String> apksToArchive = new LinkedHashMap<>();

    StandardCertificateCredentials keyStoreCredential = getKeystore(getKeyStoreId(), run.getParent());
    char[] storePassword = keyStoreCredential.getPassword().getPlainText().toCharArray();
    // TODO: add key password support
    char[] keyPassword = storePassword;
    KeyStore keyStore = keyStoreCredential.getKeyStore();
    String alias = getKeyAlias();
    PrivateKey key;
    Certificate[] certChain;
    try {
        if (getKeyAlias() == null) {
            // TODO: search all entries to find key, throw error if multiple keys
        }
        key = (PrivateKey) keyStore.getKey(alias, keyPassword);
        certChain = keyStore.getCertificateChain(alias);
    } catch (GeneralSecurityException e) {
        PrintWriter details = listener.fatalError("Error reading keystore " + getKeyStoreId());
        e.printStackTrace(details);
        throw new AbortException("Error reading keystore " + getKeyStoreId());
    }

    if (key == null || certChain == null) {
        throw new AbortException("Alias " + alias
                + " does not exist or does not point to a key and certificate in certificate credentials "
                + getKeyStoreId());
    }

    String v1SigName = alias;
    if (v1SigName == null) {
        v1SigName = keyStoreCredential.getId();
    }

    Set<FilePath> matchedApks = new TreeSet<>(Comparator.comparing(FilePath::getRemote));
    String[] globs = getSelectionGlobs();
    for (String glob : globs) {
        FilePath[] globMatch = workspace.list(glob, excludeBuilderDir);
        if (globMatch.length == 0) {
            throw new AbortException("No APKs in workspace matching " + glob);
        }
        matchedApks.addAll(Arrays.asList(globMatch));
    }

    for (FilePath unsignedApk : matchedApks) {
        unsignedApk = unsignedApk.absolutize();
        FilePath archiveDir = builderDir.child(unsignedApk.getName());
        if (archiveDir.isDirectory()) {
            archiveDir.deleteContents();
        } else {
            archiveDir.mkdirs();
        }
        String archiveDirRelName = relativeToWorkspace(workspace, archiveDir);
        String unsignedPathName = unsignedApk.getRemote();
        Pattern stripUnsignedPattern = Pattern.compile("(-?unsigned)?.apk$", Pattern.CASE_INSENSITIVE);
        Matcher stripUnsigned = stripUnsignedPattern.matcher(unsignedApk.getName());
        String strippedApkName = stripUnsigned.replaceFirst("");
        String alignedRelName = archiveDirRelName + "/" + strippedApkName + "-aligned.apk";
        String signedRelName = archiveDirRelName + "/" + strippedApkName + "-signed.apk";

        ArgumentListBuilder zipalignCommand = zipalign.commandFor(unsignedPathName, alignedRelName);
        listener.getLogger().printf("[SignApksBuilder] %s%n", zipalignCommand);
        int zipalignResult = launcher.launch().cmds(zipalignCommand).pwd(workspace).stdout(listener)
                .stderr(listener.getLogger()).join();

        if (zipalignResult != 0) {
            listener.fatalError("[SignApksBuilder] zipalign failed: exit code %d", zipalignResult);
            throw new AbortException(
                    String.format("zipalign failed on APK %s: exit code %d", unsignedPathName, zipalignResult));
        }

        FilePath alignedPath = workspace.child(alignedRelName);
        if (!alignedPath.exists()) {
            throw new AbortException(String.format("aligned APK does not exist: %s", alignedRelName));
        }

        listener.getLogger().printf("[SignApksBuilder] signing APK %s%n", alignedRelName);

        FilePath signedPath = workspace.child(signedRelName);
        final SignApkCallable signApk = new SignApkCallable(key, certChain, v1SigName, signedPath.getRemote(),
                listener);
        alignedPath.act(signApk);

        listener.getLogger().printf("[SignApksBuilder] signed APK %s%n", signedRelName);

        if (getArchiveUnsignedApks()) {
            listener.getLogger().printf("[SignApksBuilder] archiving unsigned APK %s%n", unsignedPathName);
            apksToArchive.put(archiveDirRelName + "/" + unsignedApk.getName(),
                    relativeToWorkspace(workspace, unsignedApk));
        }
        if (getArchiveSignedApks()) {
            listener.getLogger().printf("[SignApksBuilder] archiving signed APK %s%n", signedRelName);
            apksToArchive.put(signedRelName, signedRelName);
        }
    }

    listener.getLogger().println("[SignApksBuilder] finished signing APKs");

    if (apksToArchive.size() > 0) {
        run.pickArtifactManager().archive(workspace, launcher, BuildListenerAdapter.wrap(listener),
                apksToArchive);
    }
}

From source file:org.wso2.identity.integration.test.oauth2.OAuth2RequestObjectSignatureValidationTestCase.java

private void initServiceProviderKeys() throws Exception {

    KeyStore keyStore = KeyStore.getInstance("JKS");
    String jksPath = TestConfigurationProvider.getResourceLocation("IS") + File.separator + "sp"
            + File.separator + "keystores" + File.separator + "sp1KeyStore.jks";
    String jksPassword = "wso2carbon";

    keyStore.load(new FileInputStream(jksPath), jksPassword.toCharArray());

    String alias = "wso2carbon";

    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
            new KeyStore.PasswordProtection(jksPassword.toCharArray()));
    sp1PrivateKey = (RSAPrivateKey) pkEntry.getPrivateKey();

    // Load certificate chain
    Certificate[] chain = keyStore.getCertificateChain(alias);
    sp1X509PublicCert = (X509Certificate) chain[0];

    // Use another keystore to get sp2 private key.
    jksPath = TestConfigurationProvider.getResourceLocation("IS") + File.separator + "sp" + File.separator
            + "keystores" + File.separator + "sp2KeyStore.jks";

    keyStore.load(new FileInputStream(jksPath), jksPassword.toCharArray());

    pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
            new KeyStore.PasswordProtection(jksPassword.toCharArray()));
    sp2PrivateKey = (RSAPrivateKey) pkEntry.getPrivateKey();
}

From source file:eu.europa.esig.dss.x509.KeyStoreCertificateSource.java

public List<CertificateToken> populate() {
    List<CertificateToken> list = new ArrayList<CertificateToken>();
    try {//  ww  w.j  a  v  a2 s . com
        KeyStore keyStore = getKeyStore();
        Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            final Certificate certificate = keyStore.getCertificate(alias);
            if (certificate != null) {
                X509Certificate x509Certificate = (X509Certificate) certificate;
                logger.debug("Alias " + alias + " Cert " + x509Certificate.getSubjectDN());

                CertificateToken certToken = certPool.getInstance(new CertificateToken(x509Certificate),
                        CertificateSourceType.OTHER);
                list.add(certToken);
            }
            Certificate[] certificateChain = keyStore.getCertificateChain(alias);
            if (certificateChain != null) {
                for (Certificate chainCert : certificateChain) {
                    logger.debug("Alias " + alias + " Cert " + ((X509Certificate) chainCert).getSubjectDN());
                    CertificateToken certToken = certPool.getInstance(
                            new CertificateToken((X509Certificate) chainCert),
                            CertificateSourceType.OCSP_RESPONSE);
                    if (!list.contains(certToken)) {
                        list.add(certToken);
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new DSSEncodingException(MSG.CERTIFICATE_CANNOT_BE_READ, e);
    }
    return list;
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testSwingParent2() throws Exception {
    Security.addProvider(new BeIDProvider());

    MyFrame myFrame = new MyFrame();

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(myFrame);/* w  w  w  .  j ava  2  s  .  co  m*/

    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    Certificate[] certificateChain = keyStore.getCertificateChain("Authentication");
    signature.initVerify(certificateChain[0]);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testNonRepudiationSignature() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//  www .  ja v a 2 s .  com
    PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(signPrivateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    assertNotNull(signatureValue);

    Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature");
    assertNotNull(signCertificateChain);
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testNonRepudiationSignaturePPDU() throws Exception {

    CCID.riskPPDU(true);/*  ww  w  . ja va2  s .  c  om*/

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(signPrivateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    assertNotNull(signatureValue);

    Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature");
    assertNotNull(signCertificateChain);
}