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.oauth.endpoint.jwks.JwksEndpoint.java

@GET
@Path(value = "/jwks")
@Produces(MediaType.APPLICATION_JSON)/* w  w  w.j a v  a  2s.c o  m*/
public String jwks() {

    String tenantDomain = null;
    int tenantId = -1;
    Object tenantObj = IdentityUtil.threadLocalProperties.get().get(OAuthConstants.TENANT_NAME_FROM_CONTEXT);
    if (tenantObj != null) {
        tenantDomain = (String) tenantObj;
    }
    if (StringUtils.isEmpty(tenantDomain)) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    RSAPublicKey publicKey = null;
    JSONObject jwksJson = new JSONObject();
    FileInputStream file = null;
    try {
        tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
        if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
            file = new FileInputStream(
                    CarbonUtils.getServerConfiguration().getFirstProperty("Security.KeyStore.Location"));
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            String password = CarbonUtils.getServerConfiguration().getInstance()
                    .getFirstProperty("Security.KeyStore.Password");
            keystore.load(file, password.toCharArray());
            String alias = CarbonUtils.getServerConfiguration().getInstance()
                    .getFirstProperty("Security.KeyStore.KeyAlias");
            // Get certificate of public key
            Certificate cert = keystore.getCertificate(alias);
            // Get public key
            publicKey = (RSAPublicKey) cert.getPublicKey();
        } else {

            if (tenantId < 1 && tenantId != -1234) {
                String errorMesage = "The tenant is not existing";
                log.error(errorMesage);
                return errorMesage;
            }
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            KeyStore keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            // Get certificate of public key
            Certificate cert = keyStore.getCertificate(tenantDomain);
            publicKey = (RSAPublicKey) cert.getPublicKey();

        }
        String modulus = base64EncodeUint(publicKey.getModulus());
        String exponent = base64EncodeUint(publicKey.getPublicExponent());
        String kty = publicKey.getAlgorithm();
        JSONArray jwksKeyArray = new JSONArray();
        JSONObject jwksKeys = new JSONObject();
        jwksKeys.put("kty", kty);
        jwksKeys.put("alg", alg);
        jwksKeys.put("use", use);
        jwksKeys.put("kid", OAuth2Util.getThumbPrint(tenantDomain, tenantId));
        jwksKeys.put("n", modulus);
        jwksKeys.put("e", exponent);
        jwksKeyArray.put(jwksKeys);
        jwksJson.put("keys", jwksKeyArray);
    } catch (Exception e) {
        String errorMesage = "Error while generating the keyset for " + tenantDomain + " tenant domain.";
        log.error(errorMesage, e);
        return errorMesage;
    } finally {
        IdentityIOStreamUtils.closeInputStream(file);
    }

    return jwksJson.toString();
}

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

@Test
public void testPSSPrefix() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//  w  w  w.j  a  v a  2s. c o  m
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA1withRSAandMGF1");
    signature.initSign(authnPrivateKey);

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

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) authnPublicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    String paddedMessage = new String(Hex.encodeHex(messageBigInteger.toByteArray()));
    LOG.debug("padded message: " + paddedMessage);
    assertTrue(paddedMessage.endsWith("bc"));
}

From source file:test.integ.be.agiv.security.ClaimsAwareServiceTest.java

@Test
public void testSecurityFrameworkBeIDCertificate() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);// w w w  .ja  va2  s . c om
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate certificate = (X509Certificate) keyStore.getCertificate("Authentication");
    assertNotNull(privateKey);
    assertNotNull(certificate);

    Service service = ClaimsAwareServiceFactory.getInstance();
    // WS-Addressing via JAX-WS
    IService iservice = service.getWS2007FederationHttpBindingIService(new AddressingFeature());

    BindingProvider bindingProvider = (BindingProvider) iservice;

    AGIVSecurity agivSecurity = new AGIVSecurity(
            "https://auth.beta.agiv.be/ipsts/Services/DaliSecurityTokenServiceConfiguration.svc/CertificateMessage",
            "https://auth.beta.agiv.be/sts/Services/SalvadorSecurityTokenServiceConfiguration.svc/IWSTrust13",
            AGIVSecurity.BETA_REALM, certificate, privateKey);
    agivSecurity.enable(bindingProvider, ClaimsAwareServiceFactory.SERVICE_LOCATION,
            ClaimsAwareServiceFactory.SERVICE_REALM);

    ArrayOfClaimInfo result = iservice.getData(0);

    List<ClaimInfo> claims = result.getClaimInfo();
    for (ClaimInfo claim : claims) {
        LOG.debug(claim.getName() + " = " + claim.getValue());
    }

    agivSecurity.cancelSecureConversationTokens();
}

From source file:org.wso2.carbon.webapp.authenticator.framework.authenticator.JWTAuthenticator.java

@Override
public AuthenticationInfo authenticate(Request request, Response response) {
    String requestUri = request.getRequestURI();
    SignedJWT jwsObject;/*from  ww  w . j  av  a 2 s .  c om*/
    String username;
    String tenantDomain;
    int tenantId;
    String issuer;

    AuthenticationInfo authenticationInfo = new AuthenticationInfo();
    if (requestUri == null || "".equals(requestUri)) {
        authenticationInfo.setStatus(Status.CONTINUE);
    }
    if (requestUri == null) {
        requestUri = "";
    }
    StringTokenizer tokenizer = new StringTokenizer(requestUri, "/");
    String context = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
    if (context == null || "".equals(context)) {
        authenticationInfo.setStatus(Status.CONTINUE);
    }

    try {
        String authorizationHeader = request.getHeader(JWT_ASSERTION_HEADER);
        jwsObject = SignedJWT.parse(authorizationHeader);
        username = jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_USERNAME);
        tenantDomain = MultitenantUtils.getTenantDomain(username);
        tenantId = Integer.parseInt(jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_TENANT_ID));
        issuer = jwsObject.getJWTClaimsSet().getIssuer();
    } catch (ParseException e) {
        log.error("Error occurred while parsing JWT header.", e);
        authenticationInfo.setMessage("Error occurred while parsing JWT header");
        return authenticationInfo;
    }
    try {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        IssuerAlias issuerAlias = new IssuerAlias(issuer, tenantDomain);
        PublicKey publicKey = publicKeyHolder.get(issuerAlias);
        if (publicKey == null) {
            loadTenantRegistry(tenantId);
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                String alias = properties == null ? null : properties.getProperty(issuer);
                if (alias != null && !alias.isEmpty()) {
                    ServerConfiguration serverConfig = CarbonUtils.getServerConfiguration();
                    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                    String trustStorePath = serverConfig.getFirstProperty(DEFAULT_TRUST_STORE_LOCATION);
                    String trustStorePassword = serverConfig.getFirstProperty(DEFAULT_TRUST_STORE_PASSWORD);
                    keyStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());
                    java.security.cert.Certificate certificate = keyStore.getCertificate(alias);
                    publicKey = certificate == null ? null : certificate.getPublicKey();
                } else {
                    authenticationInfo.setStatus(Status.FAILURE);
                    return authenticationInfo;
                }
            } else {
                String ksName = tenantDomain.trim().replace('.', '-');
                String jksName = ksName + ".jks";
                publicKey = keyStoreManager.getKeyStore(jksName).getCertificate(tenantDomain).getPublicKey();
            }
            if (publicKey != null) {
                issuerAlias = new IssuerAlias(tenantDomain);
                publicKeyHolder.put(issuerAlias, publicKey);
            }
        }
        //Get the filesystem keystore default primary certificate
        JWSVerifier verifier = null;
        if (publicKey != null) {
            verifier = new RSASSAVerifier((RSAPublicKey) publicKey);
        }
        if (verifier != null && jwsObject.verify(verifier)) {
            username = MultitenantUtils.getTenantAwareUsername(username);
            UserStoreManager userStore = AuthenticatorFrameworkDataHolder.getInstance().getRealmService()
                    .getTenantUserRealm(tenantId).getUserStoreManager();
            if (userStore.isExistingUser(username)) {
                authenticationInfo.setTenantId(tenantId);
                authenticationInfo.setUsername(username);
                authenticationInfo.setTenantDomain(tenantDomain);
                authenticationInfo.setStatus(Status.CONTINUE);
            } else {
                authenticationInfo.setStatus(Status.FAILURE);
            }
        } else {
            authenticationInfo.setStatus(Status.FAILURE);
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while obtaining the user.", e);
        authenticationInfo.setStatus(Status.FAILURE);
    } catch (Exception e) {
        log.error("Error occurred while verifying the JWT header.", e);
        authenticationInfo.setStatus(Status.FAILURE);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    return authenticationInfo;
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 *
 * @param keystore/*from  w  w  w.j a  va2s .co  m*/
 * @param serialNumber
 * @param issuer
 * @return a certificate/alias pair from the keystore, having the given issuer and serialNumber
 * @throws KeyStoreException
 * @throws SAMLEngineException
 */
public static CertificateAliasPair getCertificatePair(KeyStore keystore, String serialNumber, String issuer)
        throws KeyStoreException, SAMLEngineException {
    String alias = null;
    String aliasCert;
    X509Certificate certificate;
    boolean find = false;
    LOG.debug("cherche dans " + keystore.toString() + " numSerie=" + serialNumber + " issuer=" + issuer);
    for (final Enumeration<String> e = keystore.aliases(); e.hasMoreElements() && !find;) {
        aliasCert = e.nextElement();
        certificate = (X509Certificate) keystore.getCertificate(aliasCert);

        final String serialNum = certificate.getSerialNumber().toString(16);

        Principal p = certificate.getIssuerDN();
        String name = p.getName();

        X500Name issuerDN = new X500Name(name);
        X500Name issuerDNConf = new X500Name(issuer);

        if (serialNum.equalsIgnoreCase(serialNumber)
                && X500PrincipalUtil.principalEquals(issuerDN, issuerDNConf)) {
            alias = aliasCert;
            find = true;
        } else {
            LOG.debug("pas pareil numSerie=" + serialNum + " ou issuer=" + name);
        }
    }
    if (!find) {
        throw new SAMLEngineException(
                "Certificate " + issuer + "/" + serialNumber + " cannot be found in keystore ");
    }
    certificate = (X509Certificate) keystore.getCertificate(alias);
    return new CertificateAliasPair(certificate, alias);

}

From source file:mitm.djigzo.web.pages.admin.SSLCertificateManager.java

public void onValidateForm() {
    if (password != null && file != null) {
        try {/*  w w  w  . ja  va 2s  .  c  o m*/
            KeyStore keyStore = getKeyStore();

            boolean keyFound = false;
            boolean validForSSL = true;

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

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

                if (keyStore.getKey(alias, null) != null) {
                    Certificate certificate = keyStore.getCertificate(alias);

                    if (!(certificate instanceof X509Certificate)) {
                        continue;
                    }

                    /*
                     * Check if the certificate is valid for SSL
                     */
                    X509CertificateInspector inspector = new X509CertificateInspector(
                            (X509Certificate) certificate);

                    Set<ExtendedKeyUsageType> extendedKeyUsage = inspector.getExtendedKeyUsage();

                    if (extendedKeyUsage != null
                            && !(extendedKeyUsage.contains(ExtendedKeyUsageType.ANYKEYUSAGE)
                                    || extendedKeyUsage.contains(ExtendedKeyUsageType.SERVERAUTH))) {
                        validForSSL = false;
                    }

                    Set<KeyUsageType> keyUsage = inspector.getKeyUsage();

                    if (keyUsage != null && !(keyUsage.contains(KeyUsageType.KEYAGREEMENT)
                            || keyUsage.contains(KeyUsageType.KEYENCIPHERMENT))) {
                        validForSSL = false;
                    }

                    keyFound = true;

                    break;
                }
            }

            if (!keyFound) {
                form.recordError(upload, "The PFX file does not contain a key.");
            } else {
                if (!validForSSL) {
                    form.recordError(upload, "The certificate contained in the PFX file is not valid for SSL");
                }
            }
        } catch (Exception e) {
            /*
             * loading a PFX can sometime result in a ClassCastException so we catch Exception.
             */
            form.recordError(upload, "The PFX file could not be read. Message: " + e.getMessage());

            logger.error("File is not a valid PFX file.", e);
        }
    }
}

From source file:org.sonatype.flexmojos.air.SignAirMojo.java

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException, MojoFailureException {
    AIRPackager airPackager = new AIRPackager();
    try {//from w  w  w  . j av a 2  s  . co  m
        String c = this.classifier == null ? "" : "-" + this.classifier;
        File output = new File(project.getBuild().getDirectory(),
                project.getBuild().getFinalName() + c + "." + AIR);
        airPackager.setOutput(output);
        airPackager.setDescriptor(getAirDescriptor());

        KeyStore keyStore = KeyStore.getInstance(storetype);
        keyStore.load(new FileInputStream(keystore.getAbsolutePath()), storepass.toCharArray());
        String alias = keyStore.aliases().nextElement();
        airPackager.setPrivateKey((PrivateKey) keyStore.getKey(alias, storepass.toCharArray()));
        airPackager.setSignerCertificate(keyStore.getCertificate(alias));
        airPackager.setCertificateChain(keyStore.getCertificateChain(alias));
        if (this.timestampURL != null) {
            airPackager.setTimestampURL(TIMESTAMP_NONE.equals(this.timestampURL) ? null : this.timestampURL);
        }

        String packaging = project.getPackaging();
        if (AIR.equals(packaging)) {
            Set<Artifact> deps = project.getDependencyArtifacts();
            for (Artifact artifact : deps) {
                if (SWF.equals(artifact.getType())) {
                    File source = artifact.getFile();
                    String path = source.getName();
                    if (stripVersion && path.contains(artifact.getVersion())) {
                        path = path.replace("-" + artifact.getVersion(), "");
                    }
                    getLog().debug("  adding source " + source + " with path " + path);
                    airPackager.addSourceWithPath(source, path);
                }
            }
        } else if (SWF.equals(packaging)) {
            File source = project.getArtifact().getFile();
            String path = source.getName();
            getLog().debug("  adding source " + source + " with path " + path);
            airPackager.addSourceWithPath(source, path);
        } else {
            throw new MojoFailureException("Unexpected project packaging " + packaging);
        }

        if (includeFiles == null && includeFileSets == null) {
            includeFileSets = resources.toArray(new FileSet[0]);
        }

        if (includeFiles != null) {
            for (final String includePath : includeFiles) {
                String directory = project.getBuild().getOutputDirectory();
                addSourceWithPath(airPackager, directory, includePath);
            }
        }

        if (includeFileSets != null) {
            for (FileSet set : includeFileSets) {
                DirectoryScanner scanner = new DirectoryScanner();
                scanner.setBasedir(set.getDirectory());
                scanner.setIncludes((String[]) set.getIncludes().toArray(new String[0]));
                scanner.setExcludes((String[]) set.getExcludes().toArray(new String[0]));
                scanner.addDefaultExcludes();
                scanner.scan();

                String[] files = scanner.getIncludedFiles();
                for (String path : files) {
                    addSourceWithPath(airPackager, set.getDirectory(), path);
                }
            }
        }

        if (classifier != null) {
            projectHelper.attachArtifact(project, project.getArtifact().getType(), classifier, output);
        } else if (SWF.equals(packaging)) {
            projectHelper.attachArtifact(project, AIR, output);
        } else {
            project.getArtifact().setFile(output);
        }

        final List<Message> messages = new ArrayList<Message>();

        airPackager.setListener(new Listener() {
            public void message(final Message message) {
                messages.add(message);
            }

            public void progress(final int soFar, final int total) {
                getLog().info("  completed " + soFar + " of " + total);
            }
        });

        airPackager.createAIR();

        if (messages.size() > 0) {
            for (final Message message : messages) {
                getLog().error("  " + message.errorDescription);
            }

            throw new MojoExecutionException("Error creating AIR application");
        } else {
            getLog().info("  AIR package created: " + output.getAbsolutePath());
        }
    } catch (MojoExecutionException e) {
        // do not handle
        throw e;
    } catch (Exception e) {
        throw new MojoExecutionException("Error invoking AIR api", e);
    } finally {
        airPackager.close();
    }
}

From source file:com.microsoft.aad.adal.testapp.MainActivity.java

public void initDeviceCertificateMock() throws NoSuchAlgorithmException, UnrecoverableKeyException,
        CertificateException, KeyStoreException, IOException {
    KeyStore keystore = loadTestCertificate();
    Key key = keystore.getKey(TEST_CERT_ALIAS, PKCS12_PASS.toCharArray());
    RSAPrivateKey privateKey = (RSAPrivateKey) key;
    Certificate cert = keystore.getCertificate(TEST_CERT_ALIAS);
    RSAPublicKey publicKey = (RSAPublicKey) cert.getPublicKey();
    MockDeviceCertProxy.sValidIssuer = true;
    MockDeviceCertProxy.sPrivateKey = privateKey;
    MockDeviceCertProxy.sPublicKey = publicKey;
    MockDeviceCertProxy.sThumbPrint = "test";
    MockDeviceCertProxy.sCertificate = (X509Certificate) cert;
    AuthenticationSettings.INSTANCE.setDeviceCertificateProxyClass(MockDeviceCertProxy.class);
}

From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java

public void removeCertFromStore(String alias, String keyStoreName) throws SecurityConfigException {
    try {/*  w w w. j a  v  a  2s  . com*/
        if (keyStoreName == null) {
            throw new SecurityConfigException("Key Store name can't be null");
        }

        KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
        KeyStore ks = keyMan.getKeyStore(keyStoreName);

        if (ks.getCertificate(alias) == null) {
            return;
        }

        ks.deleteEntry(alias);
        keyMan.updateKeyStore(keyStoreName, ks);
    } catch (SecurityConfigException e) {
        throw e;
    } catch (Exception e) {
        String msg = "Error when removing cert from store";
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }
}

From source file:org.wso2.carbon.identity.entitlement.pep.agent.wsxacml.WSXACMLEntitlementServiceClient.java

/**
 * Create basic X509 credentials using server configuration
 *
 * @return basicX509Credential//from   ww  w. j  a v  a  2 s . c  o m
 */
private BasicX509Credential createBasicCredentials() {

    PrivateKey issuerPK = null;
    Certificate certificate = null;
    ServerConfiguration serverConfig = ServerConfiguration.getInstance();
    String ksPassword = serverConfig.getFirstProperty("Security.KeyStore.Password");
    String ksLocation = serverConfig.getFirstProperty("Security.KeyStore.Location");
    String keyAlias = serverConfig.getFirstProperty("Security.KeyStore.KeyAlias");
    String ksType = serverConfig.getFirstProperty("Security.KeyStore.Type");
    String privateKeyPassword = serverConfig.getFirstProperty("Security.KeyStore.KeyPassword");

    try {
        FileInputStream fis = new FileInputStream(ksLocation);
        BufferedInputStream bis = new BufferedInputStream(fis);
        KeyStore keyStore = KeyStore.getInstance(ksType);

        keyStore.load(bis, ksPassword.toCharArray());
        bis.close();
        issuerPK = (PrivateKey) keyStore.getKey(keyAlias, privateKeyPassword.toCharArray());
        certificate = keyStore.getCertificate(keyAlias);

    } catch (KeyStoreException e) {
        log.error("Error in getting a keystore.", e);
    } catch (FileNotFoundException e) {
        log.error("Error in reading the keystore file from given the location.", e);
    } catch (CertificateException e) {
        log.error("Error in creating a X.509 certificate.", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Error in loading the keystore.", e);
    } catch (IOException e) {
        log.error("Error in reading keystore file.", e);
    } catch (UnrecoverableKeyException e) {
        log.error("Error in getting the private key.", e);
    }

    BasicX509Credential basicCredential = new BasicX509Credential();
    basicCredential.setEntityCertificate((java.security.cert.X509Certificate) certificate);
    basicCredential.setPrivateKey(issuerPK);

    return basicCredential;
}