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:org.zaproxy.zap.extension.dynssl.DynamicSSLPanel.java

private void setRootca(KeyStore rootca) {
    this.rootca = rootca;
    final StringWriter sw = new StringWriter();
    if (rootca != null) {
        try {/*from  ww  w .j  a va2  s  . c  o m*/
            final Certificate cert = rootca.getCertificate(SslCertificateService.ZAPROXY_JKS_ALIAS);
            try (final PemWriter pw = new PemWriter(sw)) {
                pw.writeObject(new JcaMiscPEMGenerator(cert));
                pw.flush();
            }
        } catch (final Exception e) {
            logger.error("Error while extracting public part from generated Root CA certificate.", e);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Certificate defined.\n" + sw.toString());
    }
    txt_PubCert.setText(sw.toString());
}

From source file:org.codice.ddf.security.validator.pki.PKITokenValidatorTest.java

@Before
public void setup() {
    pkiTokenValidator = new PKITokenValidator();
    pkiTokenValidator.setSignaturePropertiesPath(
            PKITokenValidatorTest.class.getResource("/signature.properties").getPath());
    pkiTokenValidator.setRealms(Arrays.asList("karaf"));
    pkiTokenValidator.init();/*from   w  ww  .j  a  v  a2s .  c o  m*/

    try {
        KeyStore trustStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType"));
        InputStream trustFIS = PKITokenValidatorTest.class.getResourceAsStream("/serverKeystore.jks");
        try {
            trustStore.load(trustFIS, "changeit".toCharArray());
        } catch (CertificateException e) {
            fail(e.getMessage());
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }
        Certificate[] certs = trustStore.getCertificateChain("localhost");
        certificates = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            certificates[i] = (X509Certificate) certs[i];
        }

        trustStore = KeyStore.getInstance(System.getProperty(SecurityConstants.KEYSTORE_TYPE));
        trustFIS = PKITokenValidatorTest.class.getResourceAsStream("/badKeystore.jks");
        try {
            trustStore.load(trustFIS, "changeit".toCharArray());
        } catch (CertificateException e) {
            fail(e.getMessage());
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }
        certs = trustStore.getCertificateChain("badhost");
        badCertificates = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            badCertificates[i] = (X509Certificate) certs[i];
        }
        merlin = new Merlin(
                PropertiesLoader.loadProperties(
                        PKITokenValidatorTest.class.getResource("/signature.properties").getPath()),
                PKITokenValidator.class.getClassLoader(), null);

        KeyStore keystore = KeyStore.getInstance(System.getProperty(SecurityConstants.KEYSTORE_TYPE));
        try (InputStream keystoreIS = PKITokenValidatorTest.class.getResourceAsStream("/test-user.jks")) {
            keystore.load(keystoreIS, "changeit".toCharArray());
        }
        Certificate cert = keystore.getCertificate("test");
        userCertificates = new X509Certificate[] { (X509Certificate) cert };

    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:org.apache.stratos.custom.handlers.granttype.ClientCredentialsGrantHandler.java

protected String signJWTWithRSA(String payLoad, JWSAlgorithm jwsAlgorithm, OAuthTokenReqMessageContext request)
        throws IdentityOAuth2Exception {
    try {//from   www .  ja  va2  s  .  co  m
        String tenantDomain = request.getOauth2AccessTokenReqDTO().getTenantDomain();
        int tenantId = request.getTenantID();
        if (tenantDomain == null) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
        if (tenantId == 0) {
            tenantId = MultitenantConstants.SUPER_TENANT_ID;
        }
        Key privateKey = null;

        if (!(privateKeys.containsKey(tenantId))) {
            // get tenant's key store manager
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                // derive key store name
                String ksName = tenantDomain.trim().replace(".", "-");
                String jksName = ksName + ".jks";
                // obtain private key
                privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain);

            } else {
                try {
                    privateKey = tenantKSM.getDefaultPrivateKey();
                } catch (Exception e) {
                    log.error("Error while obtaining private key for super tenant", e);
                }
            }
            if (privateKey != null) {
                privateKeys.put(tenantId, privateKey);
            }
        } else {
            privateKey = privateKeys.get(tenantId);
        }

        Certificate publicCert;

        if (!(publicCerts.containsKey(tenantId))) {
            // get tenant's key store manager
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            KeyStore keyStore;
            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                // derive key store name
                String ksName = tenantDomain.trim().replace(".", "-");
                String jksName = ksName + ".jks";
                keyStore = tenantKSM.getKeyStore(jksName);
                publicCert = keyStore.getCertificate(tenantDomain);
            } else {
                publicCert = tenantKSM.getDefaultPrimaryCertificate();
            }
            if (publicCert != null) {
                publicCerts.put(tenantId, publicCert);
            }
        } else {
            publicCert = publicCerts.get(tenantId);
        }

        JWSSigner signer = new RSASSASigner((RSAPrivateKey) privateKey);
        SignedJWT signedJWT = new SignedJWT(new JWSHeader(jwsAlgorithm),
                PlainJWT.parse(payLoad).getJWTClaimsSet());
        signedJWT.sign(signer);
        return signedJWT.serialize();
    } catch (KeyStoreException e) {
        log.error("Error in obtaining tenant's keystore", e);
        throw new IdentityOAuth2Exception("Error in obtaining tenant's keystore", e);
    } catch (JOSEException e) {
        log.error("Error in obtaining tenant's keystore", e);
        throw new IdentityOAuth2Exception("Error in obtaining tenant's keystore", e);
    } catch (Exception e) {
        log.error("Error in obtaining tenant's keystore", e);
        throw new IdentityOAuth2Exception("Error in obtaining tenant's keystore", e);
    }
}

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

public Registration createAgentCertificate(final File authorityKeystore, String agentHostname) {
    Date epoch = new Date(0);
    KeyPair agentKeyPair = generateKeyPair();
    try {/*  w ww . j  ava 2  s  . c  om*/
        KeyStore store = loadOrCreateCAKeyStore(authorityKeystore);
        KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store
                .getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY));

        X509Certificate[] chain = new X509Certificate[3];
        chain[2] = (X509Certificate) store.getCertificate("ca-cert");
        chain[1] = (X509Certificate) intermediateEntry.getCertificate();
        chain[0] = createAgentCertificate(agentKeyPair.getPublic(), intermediateEntry.getPrivateKey(),
                chain[1].getPublicKey(), agentHostname, epoch);
        return new Registration(agentKeyPair.getPrivate(), chain);
    } catch (Exception e) {
        throw bomb("Couldn't create agent certificate", e);
    }
}

From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java

/**
 * Returns list of key aliases in given keystore.
 * /*from  ww w  . j a  v a2s.co  m*/
 * @param aKs
 * @param options
 * @return
 */
private static List<String> getAliasesList(final KeyStore aKs, final BasicSignerOptions options) {
    if (options == null) {
        throw new NullPointerException("Options are empty.");
    }
    if (aKs == null) {
        throw new NullPointerException(RES.get("error.keystoreNull"));
    }
    final List<String> tmpResult = new ArrayList<String>();
    try {
        LOGGER.info(RES.get("console.getAliases"));
        final Enumeration<String> tmpAliases = aKs.aliases();
        final boolean checkValidity = ConfigProvider.getInstance().getAsBool("certificate.checkValidity", true);
        final boolean checkKeyUsage = ConfigProvider.getInstance().getAsBool("certificate.checkKeyUsage", true);
        final boolean checkCriticalExtensions = ConfigProvider.getInstance()
                .getAsBool("certificate.checkCriticalExtensions", true);
        while (tmpAliases.hasMoreElements()) {
            String tmpAlias = tmpAliases.nextElement();
            if (aKs.isKeyEntry(tmpAlias)) {
                final Certificate tmpCert = aKs.getCertificate(tmpAlias);
                boolean tmpAddAlias = true;
                if (tmpCert instanceof X509Certificate) {
                    final X509Certificate tmpX509 = (X509Certificate) tmpCert;
                    if (checkValidity) {
                        try {
                            tmpX509.checkValidity();
                        } catch (CertificateExpiredException e) {
                            LOGGER.info(RES.get("console.certificateExpired", tmpAlias));
                            tmpAddAlias = false;
                        } catch (CertificateNotYetValidException e) {
                            LOGGER.info(RES.get("console.certificateNotYetValid", tmpAlias));
                            tmpAddAlias = false;
                        }
                    }
                    if (checkKeyUsage) {
                        // check if the certificate is supposed to be
                        // used for digital signatures
                        final boolean keyUsage[] = tmpX509.getKeyUsage();
                        if (keyUsage != null && keyUsage.length > 0) {
                            // KeyUsage ::= BIT STRING {
                            // digitalSignature (0),
                            // nonRepudiation (1),
                            // keyEncipherment (2),
                            // dataEncipherment (3),
                            // keyAgreement (4),
                            // keyCertSign (5),
                            // cRLSign (6),
                            // encipherOnly (7),
                            // decipherOnly (8) }
                            if (!(keyUsage[0] || keyUsage[1])) {
                                LOGGER.info(RES.get("console.certificateNotForSignature", tmpAlias));
                                tmpAddAlias = false;
                            }
                        }
                    }
                    // check critical extensions
                    if (checkCriticalExtensions) {
                        final Set<String> criticalExtensionOIDs = tmpX509.getCriticalExtensionOIDs();
                        if (criticalExtensionOIDs != null) {
                            for (String oid : criticalExtensionOIDs) {
                                if (!Constants.SUPPORTED_CRITICAL_EXTENSION_OIDS.contains(oid)) {
                                    LOGGER.info(
                                            RES.get("console.criticalExtensionNotSupported", tmpAlias, oid));
                                    tmpAddAlias = false;
                                }
                            }
                        }
                    }
                }
                if (tmpAddAlias) {
                    tmpResult.add(tmpAlias);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error(RES.get("console.exception"), e);
    }
    return tmpResult;
}

From source file:test.integ.be.e_contract.mycarenet.etee.SealTest.java

@Test
public void testSeal() throws Exception {
    InputStream sealInputStream = SealTest.class.getResourceAsStream("/seal-fcorneli.der");
    assertNotNull(sealInputStream);/*from   w  ww .  j a va  2 s .  co m*/
    byte[] cmsData = IOUtils.toByteArray(sealInputStream);

    // check outer signature
    byte[] data = getVerifiedContent(cmsData);

    // decrypt content

    CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(data);
    LOG.debug("content encryption algo: "
            + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId());

    RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos();
    Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients();
    RecipientInformation recipientInformation = recipients.iterator().next();
    LOG.debug("recipient info type: " + recipientInformation.getClass().getName());
    KeyTransRecipientInformation keyTransRecipientInformation = (KeyTransRecipientInformation) recipientInformation;

    // load eHealth encryption certificate
    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    aliasesEnum.nextElement(); // skip authentication certificate.
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    AsymmetricKeyParameter privKeyParams = PrivateKeyFactory.createKey(eHealthPrivateKey.getEncoded());
    BcRSAKeyTransEnvelopedRecipient recipient = new BcRSAKeyTransEnvelopedRecipient(privKeyParams);
    byte[] decryptedContent = recipientInformation.getContent(recipient);
    assertNotNull(decryptedContent);
    LOG.debug("decrypted content size: " + decryptedContent.length);

    byte[] result = getVerifiedContent(decryptedContent);
    LOG.debug("result: " + new String(result));
}

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

@Test
public void testAuthenticationSignatures() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//  w ww.  j  a va2 s  .c  om
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);

    verifySignatureAlgorithm("SHA1withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA224withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA384withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA512withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("RIPEMD128withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("RIPEMD160withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("RIPEMD256withRSA", authnPrivateKey, authnCertificate.getPublicKey());
}

From source file:org.sufficientlysecure.keychain.ui.SettingsSmartPGPAuthorityFragment.java

private boolean editAuthority(final String old_alias, final String new_alias, final int position,
        final String uri) {
    try {/*from   w ww  . j av  a2  s.  c  o m*/
        final KeyStore ks = SettingsSmartPGPAuthoritiesActivity.readKeystore(getContext());

        if (ks == null) {
            throw new KeyStoreException("no keystore found");
        }

        Certificate old_cert = null;
        if (old_alias != null) {
            old_cert = ks.getCertificate(old_alias);
            ks.deleteEntry(old_alias);
            mAuthorities.remove(old_alias);
            mAdapter.notifyItemRemoved(position);
        }

        Certificate new_cert = null;
        if (uri == null) {
            new_cert = old_cert;
        } else {
            final InputStream fis = getContext().getContentResolver().openInputStream(Uri.parse(uri));

            final CertificateFactory cf = CertificateFactory.getInstance("X.509");
            new_cert = cf.generateCertificate(fis);
            if (!(new_cert instanceof X509Certificate)) {
                Notify.create(getActivity(), "Invalid certificate", Notify.LENGTH_LONG, Notify.Style.ERROR)
                        .show();
                return false;
            }

            fis.close();
        }

        if (new_alias == null || new_cert == null) {
            Notify.create(getActivity(), "Missing alias or certificate", Notify.LENGTH_LONG, Notify.Style.ERROR)
                    .show();
            return false;
        }

        final X509Certificate x509cert = (X509Certificate) new_cert;

        x509cert.checkValidity();

        ks.setCertificateEntry(new_alias, x509cert);

        SettingsSmartPGPAuthoritiesActivity.writeKeystore(getContext(), ks);

        mAuthorities.add(new_alias);
        mAdapter.notifyItemInserted(mAuthorities.size() - 1);

        return true;

    } catch (IOException e) {
        Notify.create(getActivity(), "failed to open certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG,
                Notify.Style.ERROR).show();
    } catch (CertificateException e) {
        Notify.create(getActivity(), "invalid certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG,
                Notify.Style.ERROR).show();
    } catch (KeyStoreException e) {
        Notify.create(getActivity(), "invalid keystore (" + e.getMessage() + ")", Notify.LENGTH_LONG,
                Notify.Style.ERROR).show();
    }

    return false;
}

From source file:test.integ.be.e_contract.mycarenet.tarification.TarificationClientTest.java

@Test
public void testTarificationConsultation() throws Exception {
    // STS//from www . ja  v  a  2  s.c  om
    EHealthSTSClient client = new EHealthSTSClient(
            "https://services-acpt.ehealth.fgov.be/IAM/Saml11TokenService/Legacy/v1");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter();
    beIDKeyStoreParameter.addPPDUName("digipass 870");
    beIDKeyStoreParameter.addPPDUName("digipass 875");
    beIDKeyStoreParameter.addPPDUName("digipass 920");
    keyStore.load(beIDKeyStoreParameter);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // Tarification
    TarificationClient tarificationClient = new TarificationClient(
            "https://services-acpt.ehealth.fgov.be/MyCareNet/Tarification/v1");
    tarificationClient.setCredentials(eHealthPrivateKey, assertionString);

    ObjectFactory objectFactory = new ObjectFactory();
    SendRequestType sendRequest = objectFactory.createSendRequestType();

    DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
    GregorianCalendar issueInstantCal = new GregorianCalendar();
    DateTime issueInstantDateTime = new DateTime();
    issueInstantCal.setTime(issueInstantDateTime.toDate());
    XMLGregorianCalendar issueInstant = datatypeFactory.newXMLGregorianCalendar(issueInstantCal);
    sendRequest.setIssueInstant(issueInstant);

    // TODO...

    tarificationClient.tarificationConsultation(sendRequest);

}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * Method to update the certificate which matches the given alias.
 *
 * @param certificate: The base64 encoded certificate string.
 * @param alias        : Alias of the certificate that should be retrieved.
 * @return ://from   w  w  w  .j a v  a 2 s  . c o m
 */
public ResponseCode updateCertificate(String certificate, String alias) throws CertificateManagementException {

    InputStream certificateStream = null;
    try {
        File trustStoreFile = new File(TRUST_STORE);
        localTrustStoreStream = new FileInputStream(trustStoreFile);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD);

        if (trustStore.getCertificate(alias) == null) {
            log.error("Could not update the certificate. The certificate for alias '" + alias + "' is not found"
                    + " in the trust store.");
            return ResponseCode.CERTIFICATE_NOT_FOUND;
        }

        //Generate the certificate from the input string.
        byte[] cert = (Base64.decodeBase64(certificate.getBytes(CHARSET_UTF_8)));
        certificateStream = new ByteArrayInputStream(cert);

        if (certificateStream.available() == 0) {
            log.error("Certificate is empty for the provided alias " + alias);
            return ResponseCode.INTERNAL_SERVER_ERROR;
        }

        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        Certificate newCertificate = certificateFactory.generateCertificate(certificateStream);
        X509Certificate x509Certificate = (X509Certificate) newCertificate;

        if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
            log.error("Could not update the certificate. The certificate expired.");
            return ResponseCode.CERTIFICATE_EXPIRED;
        }
        // If the certificate is not expired, delete the existing certificate and add the new cert.
        trustStore.deleteEntry(alias);
        //Store the certificate in the trust store.
        trustStore.setCertificateEntry(alias, newCertificate);
        fileOutputStream = new FileOutputStream(trustStoreFile);
        trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD);
    } catch (IOException e) {
        throw new CertificateManagementException("Error updating certificate.", e);
    } catch (CertificateException e) {
        throw new CertificateManagementException("Error generating the certificate.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateManagementException("Error loading the keystore.", e);
    } catch (KeyStoreException e) {
        throw new CertificateManagementException("Error updating the certificate in the keystore.", e);
    } finally {
        closeStreams(fileOutputStream, certificateStream, localTrustStoreStream);
    }
    return ResponseCode.SUCCESS;
}