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.wso2.carbon.identity.saml.application.listener.listeners.SAMLMetadataListener.java

private String getCertFromKeyStore(String alias, String tenantDomain) {

    int tenantId = 0;
    try {/*from   ww  w. ja v a 2 s. c om*/
        tenantId = IdentitySAMLListenerComponent.getRealmService().getTenantManager().getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error getting the tenant ID for the tenant domain " + tenantDomain, e);
        }

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

    KeyStore keyStore;

    try {
        if (MultitenantConstants.SUPER_TENANT_ID != tenantId) {// for tenants, load public key from their
            // generated key store
            keyStore = keyStoreManager.getKeyStore(SAMLSSOUtil.generateKSNameFromDomainName(tenantDomain));
        } else { // for super tenant, load the default pub. cert using the config. in carbon.xml
            keyStore = keyStoreManager.getPrimaryKeyStore();
        }
        X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
        return new String(Base64.encodeBase64(cert.getEncoded()));
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Error retrieving the public certificate for alias " + alias, e);
        }
    }

    return null;
}

From source file:it.cnr.icar.eric.server.security.authentication.AuthenticationServiceImpl.java

private void loadPublicKeyToCertMap() throws RegistryException {
    try {//from w ww. j av  a2s  . c  om
        KeyStore store = getKeyStore();

        for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) {
            String alias = 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:io.pivotal.springcloud.ssl.CloudFoundryCertificateTruster.java

/**
 * import trust from truststore file/*w  ww . ja va2 s.c  o m*/
 *
 * @param applicationContext
 * @param trustStore
 * @param trustStorePassword
 */
private void trustCertificatesFromStoreInternal(ConfigurableApplicationContext applicationContext,
        String trustStore, String trustStorePassword) {
    if (trustStore != null) {
        try {
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(applicationContext.getResource(trustStore).getInputStream(),
                    trustStorePassword.toCharArray());
            Enumeration<String> aliases = keystore.aliases();

            List<X509Certificate> certCollect = new ArrayList<X509Certificate>();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();

                Certificate[] certs = keystore.getCertificateChain(alias);
                if (certs != null && certs.length > 0)
                    for (Certificate cert : certs)
                        if (cert instanceof X509Certificate)
                            certCollect.add((X509Certificate) cert);

                Certificate cert = keystore.getCertificate(alias);
                if (cert != null && cert instanceof X509Certificate) {
                    certCollect.add((X509Certificate) cert);
                }
            }

            if (certCollect.size() > 0)
                sslCertificateTruster.appendToTruststoreInternal(certCollect.toArray(new X509Certificate[0]));

        } catch (Exception e) {
            log.error("trusting trustore at {}:{} failed", trustStore, trustStorePassword, e);
        }
    }
}

From source file:mitm.common.tools.PfxTool.java

private void mergePfx() throws Exception {
    if (StringUtils.isEmpty(destFile)) {
        throw new MissingOptionException(destOption.getOpt() + " is missing.");
    }/*from w ww . j a  v  a 2s. c o m*/

    if (StringUtils.isEmpty(destPassword)) {
        throw new MissingOptionException(destPasswordOption.getOpt() + " is missing.");
    }

    KeyStore inStore = loadKeyStore(inFile, true, inPassword);
    KeyStore destStore = loadKeyStore(destFile, false, destPassword);

    Enumeration<String> aliases = inStore.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        String destAlias = retainAliases ? alias : UUID.randomUUID().toString() + "_" + alias;

        if (inStore.isKeyEntry(alias)) {
            KeyStore.Entry entry = inStore.getEntry(alias,
                    new KeyStore.PasswordProtection(inPassword.toCharArray()));

            destStore.setEntry(destAlias, entry, new KeyStore.PasswordProtection(destPassword.toCharArray()));
        } else {
            Certificate certificate = inStore.getCertificate(alias);

            destStore.setCertificateEntry(destAlias, certificate);
        }
    }

    destStore.store(new FileOutputStream(destFile), destPassword.toCharArray());
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

/**
 *       ?./*from w  w  w.j  a  va2s  .com*/
 * <p/>
 * <p/>
 *    ? ?   RSA.    ?  ?
 * ?,    ?    ?.  ???   ?. ? ??
 * ?  ?  ?  ?:
 * <ol>
 * <li>  ? ?  .</li>
 * <li>   ???  ?   ? ?.</li>
 * <li> ? ?  ?.</li>
 * <li> ?     ???.</li>
 * <li>  ? ? .</li>
 * <li>   ,  ?       ?.</li>
 * </ol>
 * <p/>
 * .. ?? ?,   ,  ?   ???,  ??, ?.  ?
 * ?  ? ? ? ?   ?.  ?  ?,  
 *   ,    ,    .
 * <p/>
 * ? ? ? ?  ? ??  ? ?,  ?? ? ???, 
 *  ?   ?.
 *
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 */
static void loadCertificate() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException {
    if (!started) {
        synchronized (CryptoProvider.class) {
            if (!started) {
                final long startMs = System.currentTimeMillis();
                final KeyStore keystore = KeyStore.getInstance("HDImageStore");
                keystore.load(null, null);

                final Properties properties = new Properties();
                properties.setProperty("name", DEFAULT_CERT_NAME);
                properties.setProperty("pass", DEFAULT_CERT_PASS);

                final File userHome = new File(System.getProperty("user.home"));
                final File keyFile = new File(userHome, "gses-key.properties");
                if (!keyFile.exists()) {
                    log.warn(keyFile
                            + "  , ???  ? ??");
                } else {
                    final FileInputStream is = new FileInputStream(keyFile);
                    properties.load(is);
                    is.close();
                }
                final String certName_ = properties.getProperty("name");
                final String certPass_ = properties.getProperty("pass");

                privateKey = ((PrivateKey) keystore.getKey(certName_, certPass_.toCharArray()));
                cert = ((X509Certificate) keystore.getCertificate(certName_));

                try {
                    cert.checkValidity();
                    log.info(" ?  " + cert.getNotAfter()
                            + " ? " + cert.getSubjectDN().getName());
                } catch (CertificateExpiredException e) {
                    log.error(
                            "? ? ?? ? ? "
                                    + cert.getSubjectDN().getName());
                    cert = null;
                    privateKey = null;
                } catch (CertificateNotYetValidException e) {
                    log.error("? ? ? ?? ? ? "
                            + cert.getSubjectDN().getName());
                    cert = null;
                    privateKey = null;
                }
                if ((privateKey != null) && (cert != null)) {
                    started = true;
                }
                if (log.isDebugEnabled()) {
                    log.debug("LOAD CERTIFICATE: " + (System.currentTimeMillis() - startMs) + "ms");
                }
            }
        }
    }
}

From source file:org.votingsystem.web.ejb.SignatureBean.java

public void init() throws Exception {
    Properties properties = new Properties();
    URL res = Thread.currentThread().getContextClassLoader().getResource("KeyStore.properties");
    log.info("init - res: " + res.toURI());
    properties.load(res.openStream());// www  .  j  a v a2s  . c  om
    keyAlias = properties.getProperty("vs.signKeyAlias");
    password = properties.getProperty("vs.signKeyPassword");
    String keyStoreFileName = properties.getProperty("vs.keyStoreFile");
    res = Thread.currentThread().getContextClassLoader().getResource(keyStoreFileName);
    File keyStoreFile = FileUtils.getFileFromBytes(IOUtils.toByteArray(res.openStream()));
    signedMailGenerator = new SMIMESignedGeneratorVS(FileUtils.getBytesFromFile(keyStoreFile), keyAlias,
            password.toCharArray(), ContextVS.SIGN_MECHANISM);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(keyStoreFile), password.toCharArray());
    certChain = new ArrayList<>();
    for (java.security.cert.Certificate certificate : keyStore.getCertificateChain(keyAlias)) {
        checkAuthorityCertDB((X509Certificate) certificate);
        certChain.add((X509Certificate) certificate);
    }
    keyStorePEMCerts = CertUtils.getPEMEncoded(certChain);
    localServerCertSigner = (X509Certificate) keyStore.getCertificate(keyAlias);
    currencyAnchors = new HashSet<>();
    currencyAnchors.add(new TrustAnchor(localServerCertSigner, null));
    Query query = dao.getEM().createNamedQuery("findCertBySerialNumber").setParameter("serialNumber",
            localServerCertSigner.getSerialNumber().longValue());
    serverCertificateVS = dao.getSingleResult(CertificateVS.class, query);
    serverPrivateKey = (PrivateKey) keyStore.getKey(keyAlias, password.toCharArray());
    encryptor = new Encryptor(localServerCertSigner, serverPrivateKey);
    serverName = config.getServerName();
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

@Override
/**//from ww  w . j  a v a 2  s .  co  m
 * 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)
 */
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 new X509Certificate[0];
        }
    } 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.wso2.carbon.identity.oauth2.token.handlers.SAML2BearerGrantTypeHandler.java

/**
 * We're validating the SAML token that we receive from the request. Through the assertion parameter is the POST
 * request. A request format that we handle here looks like,
 * <p/>//from   w  ww . j  a  va2s  .c  o m
 * POST /token.oauth2 HTTP/1.1
 * Host: as.example.com
 * Content-Type: application/x-www-form-urlencoded
 * <p/>
 * grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Asaml2-bearer&
 * assertion=PHNhbWxwOl...[omitted for brevity]...ZT4
 *
 * @param tokReqMsgCtx Token message request context
 * @return true if validation is successful, false otherwise
 * @throws IdentityOAuth2Exception
 */
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    boolean isValid = false;

    try {
        // Logging the SAML token
        if (log.isDebugEnabled()) {
            log.debug("Received SAML assertion : " + new String(
                    Base64.decodeBase64(tokReqMsgCtx.getOauth2AccessTokenReqDTO().getAssertion())));
        }

        XMLObject samlObject = Util.unmarshall(
                new String(Base64.decodeBase64(tokReqMsgCtx.getOauth2AccessTokenReqDTO().getAssertion())));
        Assertion assertion = (Assertion) samlObject;
        // List<Assertion> assertions = assertion.getAssertions();

        //            Assertion assertion = null;
        //            if (assertions != null && assertions.size() > 0) {
        //                assertion = assertions.get(0);
        //            }

        if (assertion == null) {
            log.error("Assertion is null, cannot continue");
            // throw new SAML2SSOAuthenticatorException("SAMLResponse does not contain Assertions.");
            throw new Exception("Assertion is null, cannot continue");
        }

        /**
         * Validating SAML request according to criteria specified in "SAML 2.0 Bearer Assertion Profiles for
         * OAuth 2.0 - http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-14
         */

        /**
         * The Assertion's <Issuer> element MUST contain a unique identifier for the entity that issued
         * the Assertion.
         */
        if ((assertion.getIssuer() != null) && assertion.getIssuer().getValue().equals("")) {
            log.error("Issuer is empty in the SAML assertion");
            throw new Exception("Issuer is empty in the SAML assertion");
        }

        /**
         * The Assertion MUST contain <Conditions> element with an <AudienceRestriction> element with an <Audience>
         * element containing a URI reference that identifies the authorization server, or the service provider
         * SAML entity of its controlling domain, as an intended audience.  The token endpoint URL of the
         * authorization server MAY be used as an acceptable value for an <Audience> element.  The authorization
         * server MUST verify that it is an intended audience for the Assertion.
         */
        Conditions conditions = assertion.getConditions();
        if (conditions != null) {
            List<AudienceRestriction> restrictions = conditions.getAudienceRestrictions();
            if (restrictions != null && restrictions.size() > 0) {
                AudienceRestriction ar = restrictions.get(0);

                // Where to get what SPs are configured for this IdP?
                for (Audience a : ar.getAudiences()) {
                    String audienceURI = a.getAudienceURI();
                    // TODO: figure out how to get the mapping there's an audience URI that matches IdP URI
                }
            } else {
                log.error("Cannot find any AudienceRestrictions in the Assertion");
                throw new Exception("Cannot find any AudienceRestrictions in the Assertion");
            }
        } else {
            log.error("Cannot find any Conditions in the Assertion");
            throw new Exception("Cannot find any Conditions in the Assertion");
        }

        /**
         * The Assertion MUST contain a <Subject> element.  The subject MAY identify the resource owner for whom
         * the access token is being requested.  For client authentication, the Subject MUST be the "client_id"
         * of the OAuth client.  When using an Assertion as an authorization grant, the Subject SHOULD identify
         * an authorized accessor for whom the access token is being requested (typically the resource owner, or
         * an authorized delegate).  Additional information identifying the subject/principal of the transaction
         * MAY be included in an <AttributeStatement>.
         */
        if (assertion.getSubject() != null) {
            // Get user the client_id belongs to
            String token_user = OAuth2Util.getAuthenticatedUsername(
                    tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(),
                    tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientSecret());
            // User of client id should match user in subject
            if (!assertion.getSubject().getNameID().getValue().equals(token_user)) {
                log.error("NameID in Assertion doesn't match username the client id belongs to");
                throw new Exception("NameID in Assertion doesn't match username the client id belongs to");
            }
        } else {
            log.error("Cannot find a Subject in the Assertion");
            throw new Exception("Cannot find a Subject in the Assertion");
        }

        /**
         * The Assertion MUST have an expiry that limits the time window during which it can be used.  The expiry
         * can be expressed either as the NotOnOrAfter attribute of the <Conditions> element or as the NotOnOrAfter
         * attribute of a suitable <SubjectConfirmationData> element.
         */
        boolean isNotOnOrAfterFound = false;
        DateTime notOnOrAfter = null;
        if (assertion.getSubject().getSubjectConfirmations() != null) {
            List<SubjectConfirmation> sc = assertion.getSubject().getSubjectConfirmations();
            for (SubjectConfirmation s : sc) {
                notOnOrAfter = s.getSubjectConfirmationData().getNotOnOrAfter();
                isNotOnOrAfterFound = true;
            }
        }
        if (!isNotOnOrAfterFound) {
            // We didn't find any NotOnOrAfter attributes in SubjectConfirmationData. Let's look at attributes in
            // the Conditions element
            if (assertion.getConditions() != null) {
                notOnOrAfter = assertion.getConditions().getNotOnOrAfter();
                isNotOnOrAfterFound = true;
            } else {
                // At this point there can be no NotOnOrAfter attributes, according to the spec description above
                // we can safely throw the error
                log.error("Didn't find any NotOnOrAfter attribute, must have an expiry time");
                throw new Exception("Didn't find any NotOnOrAfter attribute, must have an expiry time");
            }
        }

        /**
         * The <Subject> element MUST contain at least one <SubjectConfirmation> element that allows the
         * authorization server to confirm it as a Bearer Assertion.  Such a <SubjectConfirmation> element MUST
         * have a Method attribute with a value of "urn:oasis:names:tc:SAML:2.0:cm:bearer".  The
         * <SubjectConfirmation> element MUST contain a <SubjectConfirmationData> element, unless the Assertion
         * has a suitable NotOnOrAfter attribute on the <Conditions> element, in which case the
         * <SubjectConfirmationData> element MAY be omitted. When present, the <SubjectConfirmationData> element
         * MUST have a Recipient attribute with a value indicating the token endpoint URL of the authorization
         * server (or an acceptable alias).  The authorization server MUST verify that the value of the Recipient
         * attribute matches the token endpoint URL (or an acceptable alias) to which the Assertion was delivered.
         * The <SubjectConfirmationData> element MUST have a NotOnOrAfter attribute that limits the window during
         * which the Assertion can be confirmed.  The <SubjectConfirmationData> element MAY also contain an Address
         * attribute limiting the client address from which the Assertion can be delivered.  Verification of the
         * Address is at the discretion of the authorization server.
         */
        if ((assertion.getSubject().getSubjectConfirmations() != null)
                && (assertion.getSubject().getSubjectConfirmations().size() > 0)) {
            List<SubjectConfirmation> confirmations = assertion.getSubject().getSubjectConfirmations();
            boolean bearerFound = false;
            ArrayList<String> recipientURLS = new ArrayList<String>();
            for (SubjectConfirmation c : confirmations) {
                if (c.getSubjectConfirmationData() != null) {
                    recipientURLS.add(c.getSubjectConfirmationData().getRecipient());
                }
                if (c.getMethod().equals(OAuth2Constants.OAUTH_SAML2_BEARER_METHOD)) {
                    bearerFound = true;
                }
            }
            if (!bearerFound) {
                log.error("Failed to find a SubjectConfirmation with a Method attribute having : "
                        + OAuth2Constants.OAUTH_SAML2_BEARER_METHOD);
                throw new Exception("Failed to find a SubjectConfirmation with a Method attribute having : "
                        + OAuth2Constants.OAUTH_SAML2_BEARER_METHOD);
            }
            // TODO: Verify at least one recipientURLS matches token endpoint URL
        } else {
            log.error("No SubjectConfirmation exist in Assertion");
            throw new Exception("No SubjectConfirmation exist in Assertion");
        }

        /**
         * The authorization server MUST verify that the NotOnOrAfter instant has not passed, subject to allowable
         * clock skew between systems.  An invalid NotOnOrAfter instant on the <Conditions> element invalidates
         * the entire Assertion.  An invalid NotOnOrAfter instant on a <SubjectConfirmationData> element only
         * invalidates the individual <SubjectConfirmation>.  The authorization server MAY reject Assertions with
         * a NotOnOrAfter instant that is unreasonably far in the future.  The authorization server MAY ensure
         * that Bearer Assertions are not replayed, by maintaining the set of used ID values for the length of
         * time for which the Assertion would be considered valid based on the applicable NotOnOrAfter instant.
         */
        if (notOnOrAfter.compareTo(new DateTime()) != 1) {
            // notOnOrAfter is an expired timestamp
            log.error("NotOnOrAfter is having an expired timestamp");
            throw new Exception("NotOnOrAfter is having an expired timestamp");
        }

        /**
         * The Assertion MUST be digitally signed by the issuer and the authorization server MUST verify the
         * signature.
         */
        X509CredentialImpl credImpl;

        // Use primary keystore specified in carbon.xml
        ServerConfiguration sc = ServerConfiguration.getInstance();
        KeyStore ks = KeyStore.getInstance(sc.getFirstProperty("Security.KeyStore.Type"));
        FileInputStream ksFile = new FileInputStream(sc.getFirstProperty("Security.KeyStore.Location"));
        ks.load(ksFile, sc.getFirstProperty("Security.KeyStore.Password").toCharArray());
        ksFile.close();

        String alias = sc.getFirstProperty("Security.KeyStore.KeyAlias");
        X509Certificate cert = null;
        if (alias != null) {
            cert = (X509Certificate) ks.getCertificate(alias);
            if (cert == null) {
                log.error("Cannot find certificate with the alias - " + alias);
            }
        }
        credImpl = new X509CredentialImpl(cert);
        SignatureValidator validator = new SignatureValidator(credImpl);
        validator.validate(assertion.getSignature());

        /**
         * The authorization server MUST verify that the Assertion is valid in all other respects per
         * [OASIS.saml-core-2.0-os], such as (but not limited to) evaluating all content within the Conditions
         * element including the NotOnOrAfter and NotBefore attributes, rejecting unknown condition types, etc.
         *
         * [OASIS.saml-core-2.0-os] - http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
         */
        // TODO: Throw the SAML request through the general SAML2 validation routines

        isValid = true;
    } catch (Exception e) {
        /**
         * Ideally we should handle a SAML2SSOAuthenticatorException here? Seems to be the right
         * way to go as there's no other exception class specified. Need a clear exception hierarchy here for
         * handling SAML messages.*/
        log.error(e.getMessage(), e);
    }
    return isValid;
}

From source file:io.selendroid.standalone.builder.SelendroidServerBuilder.java

private String getSigAlg() {
    String sigAlg = "MD5withRSA";
    FileInputStream in;/*from   w w  w .  j a v  a  2s  .c o  m*/
    try {
        if (serverConfiguration != null) {
            String keystoreFile = serverConfiguration.getKeystore();
            if (keystoreFile != null) {
                in = new FileInputStream(keystoreFile);

                KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
                String keystorePassword = serverConfiguration.getKeystorePassword();
                char[] keystorePasswordCharArray = (keystorePassword == null) ? null
                        : keystorePassword.toCharArray();
                if (keystorePasswordCharArray == null) {
                    throw new RuntimeException("No keystore password configured.");
                }
                keystore.load(in, keystorePasswordCharArray);
                cert509 = (X509Certificate) keystore.getCertificate(serverConfiguration.getKeystoreAlias());
                sigAlg = cert509.getSigAlgName();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING,
                String.format("Error getting signature algorithm for jarsigner. Defaulting to %s. Reason: %s",
                        sigAlg, e.getMessage()));
    }
    return sigAlg;
}

From source file:org.keycloak.testsuite.oauth.ClientAuthSignedJWTTest.java

private void testUploadKeystore(String keystoreFormat, String filePath, String keyAlias, String storePassword)
        throws Exception {
    ClientRepresentation client = getClient(testRealm.getRealm(), app3.getId()).toRepresentation();
    final String certOld = client.getAttributes().get(JWTClientAuthenticator.CERTIFICATE_ATTR);

    // Load the keystore file
    URL fileUrl = (getClass().getClassLoader().getResource(filePath));
    if (fileUrl == null) {
        throw new IOException("File not found: " + filePath);
    }// w w  w  .  j  av  a 2  s . co m
    File keystoreFile = new File(fileUrl.getFile());
    ContentType keystoreContentType = ContentType.create(Files.probeContentType(keystoreFile.toPath()));

    // Get admin access token, no matter it's master realm's admin
    OAuthClient.AccessTokenResponse accessTokenResponse = oauth.doGrantAccessTokenRequest(AuthRealm.MASTER,
            AuthRealm.ADMIN, AuthRealm.ADMIN, null, "admin-cli", null);
    assertEquals(200, accessTokenResponse.getStatusCode());

    final String url = suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/realms/"
            + testRealm.getRealm() + "/clients/" + client.getId()
            + "/certificates/jwt.credential/upload-certificate";

    // Prepare the HTTP request
    FileBody fileBody = new FileBody(keystoreFile, keystoreContentType);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody)
            .addTextBody("keystoreFormat", keystoreFormat).addTextBody("keyAlias", keyAlias)
            .addTextBody("storePassword", storePassword).addTextBody("keyPassword", "undefined").build();
    HttpPost httpRequest = new HttpPost(url);
    httpRequest.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessTokenResponse.getAccessToken());
    httpRequest.setEntity(entity);

    // Send the request
    HttpClient httpClient = HttpClients.createDefault();
    HttpResponse httpResponse = httpClient.execute(httpRequest);
    assertEquals(200, httpResponse.getStatusLine().getStatusCode());

    client = getClient(testRealm.getRealm(), client.getId()).toRepresentation();
    String pem;

    // Assert the uploaded certificate
    if (!keystoreFormat.equals(CERTIFICATE_PEM)) {
        InputStream keystoreIs = new FileInputStream(keystoreFile);
        KeyStore keyStore = getKeystore(keystoreIs, storePassword, keystoreFormat);
        keystoreIs.close();
        pem = KeycloakModelUtils.getPemFromCertificate((X509Certificate) keyStore.getCertificate(keyAlias));
    } else {
        pem = new String(Files.readAllBytes(keystoreFile.toPath()));
    }

    assertCertificate(client, certOld, pem);
}