Java Code Examples for org.wso2.carbon.core.util.KeyStoreManager#getInstance()

The following examples show how to use org.wso2.carbon.core.util.KeyStoreManager#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WSXACMLMessageReceiver.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Create basic credentials needed to generate signature using EntitlementServiceComponent
 *
 * @return basicX509Credential
 */
private static BasicX509Credential createBasicCredentials() {

    Certificate certificate = null;
    PrivateKey issuerPK = null;

    KeyStoreManager keyMan = KeyStoreManager.getInstance(-1234);

    try {
        certificate = keyMan.getDefaultPrimaryCertificate();
        issuerPK = keyMan.getDefaultPrivateKey();
    } catch (Exception e) {
        log.error("Error occurred while getting the KeyStore from KeyManger.", e);
    }

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

    return basicCredential;
}
 
Example 2
Source File: OAuthHandler.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private String extractAppIdFromIdToken(String token) {
    String appId = null;
    KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
    try {
        keyStoreManager.getDefaultPrimaryCertificate();
        JWSVerifier verifier =
                new RSASSAVerifier((RSAPublicKey) keyStoreManager.getDefaultPublicKey());
        SignedJWT jwsObject = SignedJWT.parse(token);
        if (jwsObject.verify(verifier)) {
            appId = jwsObject.getJWTClaimsSet().getStringClaim("appId");
        }

    } catch (Exception e) {
        String message = "Could not extract application id from id token";
        log.error(message, e);
    }
    return appId;
}
 
Example 3
Source File: KeyStoreAdmin.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public Key getPrivateKey(String alias, boolean isSuperTenant) throws SecurityConfigException {
    KeyStoreData[] keystores = getKeyStores(isSuperTenant);
    KeyStore keyStore = null;
    String privateKeyPassowrd = null;

    try {

        for (int i = 0; i < keystores.length; i++) {
            if (KeyStoreUtil.isPrimaryStore(keystores[i].getKeyStoreName())) {
                KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
                keyStore = keyMan.getPrimaryKeyStore();
                ServerConfiguration serverConfig = ServerConfiguration.getInstance();
                privateKeyPassowrd = serverConfig
                        .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
                return keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
            }
        }
    } catch (Exception e) {
        String msg = "Error has encounted while loading the key for the given alias " + alias;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }
    return null;
}
 
Example 4
Source File: SignKeyDataHolder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public SignKeyDataHolder() throws Exception {
    try {
        String keyAlias = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.KeyAlias");
        KeyStoreManager keyMan = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
        Certificate[] certificates = keyMan.getPrimaryKeyStore().getCertificateChain(keyAlias);
        issuerPK = keyMan.getDefaultPrivateKey();
        issuerCerts = new X509Certificate[certificates.length];
        int i = 0;
        for (Certificate certificate : certificates) {
            issuerCerts[i++] = (X509Certificate) certificate;
        }
        signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA;
        String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
        }

    } catch (Exception e) {
        throw new Exception("Error while reading the key", e);
    }

}
 
Example 5
Source File: WSXACMLMessageReceiver.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * get a org.wso2.carbon.identity.entitlement.wsxacml.X509CredentialImpl using RegistryService
 *
 * @return created X509Credential
 */
private X509CredentialImpl getPublicX509CredentialImpl() throws Exception {

    X509CredentialImpl credentialImpl;
    KeyStoreManager keyStoreManager;
    try {
        keyStoreManager = KeyStoreManager.getInstance(-1234);
        // load the default pub. cert using the configuration in carbon.xml
        java.security.cert.X509Certificate cert = keyStoreManager.getDefaultPrimaryCertificate();
        credentialImpl = new X509CredentialImpl(cert);
        return credentialImpl;
    } catch (Exception e) {
        log.error("Error instantiating an org.wso2.carbon.identity.entitlement.wsxacml.X509CredentialImpl " +
                "object for the public cert.", e);
        throw new Exception("Error instantiating an org.wso2.carbon.identity.entitlement.wsxacml.X509CredentialImpl " +
                "object for the public cert.", e);
    }
}
 
Example 6
Source File: WSXACMLMessageReceiver.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Create basic credentials needed to generate signature using EntitlementServiceComponent
 *
 * @return basicX509Credential
 */
private static BasicX509Credential createBasicCredentials() {

    Certificate certificate = null;
    PrivateKey issuerPK = null;

    KeyStoreManager keyMan = KeyStoreManager.getInstance(-1234);

    try {
        certificate = keyMan.getDefaultPrimaryCertificate();
        issuerPK = keyMan.getDefaultPrivateKey();
    } catch (Exception e) {
        log.error("Error occurred while getting the KeyStore from KeyManger.", e);
    }

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

    return basicCredential;
}
 
Example 7
Source File: KeyStoreCertificateRetriever.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * @param certificateId Alias of the certificate to be retrieved.
 * @param tenant        The tenant where the key store file should be loaded from.
 *                      If the tenant is the super tenant, the primary key store will be used.
 * @return The certificate for the given alias
 */
@Override
public X509Certificate getCertificate(String certificateId, Tenant tenant) throws CertificateRetrievingException {

    KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenant.getId());

    KeyStore keyStore;

    try {
        if (tenant.getId() != MultitenantConstants.SUPER_TENANT_ID) {
            // This is a tenant. So load the tenant key store.
            keyStore = keyStoreManager.getKeyStore(getKeyStoreName(tenant.getDomain()));
        } else {
            // This is the super tenant. So load the primary key store.
            keyStore = keyStoreManager.getPrimaryKeyStore();
        }
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(certificateId);
        return certificate;
    } catch (Exception e) {
        String errorMsg = String.format("Error occurred while retrieving the certificate for the alias '%s' " +
                "of the tenant domain '%s'." + certificateId, tenant.getDomain());
        throw new CertificateRetrievingException(errorMsg, e);
    }
}
 
Example 8
Source File: KeyStoreAdmin.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public Key getPrivateKey(String alias, boolean isSuperTenant) throws SecurityConfigException {
    KeyStoreData[] keystores = getKeyStores(isSuperTenant);
    KeyStore keyStore = null;
    String privateKeyPassowrd = null;

    try {

        for (int i = 0; i < keystores.length; i++) {
            if (KeyStoreUtil.isPrimaryStore(keystores[i].getKeyStoreName())) {
                KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
                keyStore = keyMan.getPrimaryKeyStore();
                ServerConfiguration serverConfig = ServerConfiguration.getInstance();
                privateKeyPassowrd = serverConfig
                        .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
                return keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
            }
        }
    } catch (Exception e) {
        String msg = "Error has encounted while loading the key for the given alias " + alias;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }
    return null;
}
 
Example 9
Source File: WSXACMLMessageReceiver.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * get a org.wso2.carbon.identity.entitlement.wsxacml.X509CredentialImpl using RegistryService
 *
 * @return created X509Credential
 */
private X509CredentialImpl getPublicX509CredentialImpl() throws Exception {

    X509CredentialImpl credentialImpl;
    KeyStoreManager keyStoreManager;
    try {
        keyStoreManager = KeyStoreManager.getInstance(-1234);
        // load the default pub. cert using the configuration in carbon.xml
        java.security.cert.X509Certificate cert = keyStoreManager.getDefaultPrimaryCertificate();
        credentialImpl = new X509CredentialImpl(cert);
        return credentialImpl;
    } catch (Exception e) {
        log.error("Error instantiating an org.wso2.carbon.identity.entitlement.wsxacml.X509CredentialImpl " +
                "object for the public cert.", e);
        throw new Exception("Error instantiating an org.wso2.carbon.identity.entitlement.wsxacml.X509CredentialImpl " +
                "object for the public cert.", e);
    }
}
 
Example 10
Source File: CarbonBasedTestListener.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void createKeyStore(Class realClass, WithKeyStore withKeyStore) {

        try {
            RegistryService registryService = createRegistryService(realClass, withKeyStore.tenantId(),
                                                                    withKeyStore.tenantDomain());
            ServerConfiguration serverConfigurationService = ServerConfiguration.getInstance();
            serverConfigurationService.init(realClass.getResourceAsStream("/repository/conf/carbon.xml"));
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(withKeyStore.tenantId(),
                                                                          serverConfigurationService,
                                                                          registryService);
            if (!Proxy.isProxyClass(keyStoreManager.getClass()) &&
                    !keyStoreManager.getClass().getName().contains("EnhancerByMockitoWithCGLIB")  ) {
                KeyStore keyStore = ReadCertStoreSampleUtil.createKeyStore(getClass());
                org.wso2.carbon.identity.testutil.Whitebox.setInternalState(keyStoreManager, "primaryKeyStore",
                                                                            keyStore);
                org.wso2.carbon.identity.testutil.Whitebox.setInternalState(keyStoreManager, "registryKeyStore",
                                                                            keyStore);
            }
            CarbonCoreDataHolder.getInstance().setRegistryService(registryService);
            CarbonCoreDataHolder.getInstance().setServerConfigurationService(serverConfigurationService);
        } catch (Exception e) {
            throw new TestCreationException(
                    "Unhandled error while reading cert for test class:  " + realClass.getName(), e);
        }
    }
 
Example 11
Source File: KeyStoreAdmin.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the {@link KeyStore} object of the given keystore name.
 *
 * @param keyStoreName name of the keystore.
 * @return {@link KeyStore} object.
 * @throws Exception if retrieving the keystore fails.
 */
public KeyStore getKeyStore(String keyStoreName) throws Exception {

    if (isTrustStore(keyStoreName)) {
        return getTrustStore();
    } else {
        KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
        return keyMan.getKeyStore(keyStoreName);
    }
}
 
Example 12
Source File: SecurityConfigAdmin.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public Properties getServerCryptoProperties(String privateStore, String[] trustedCertStores)
        throws Exception {

    Properties props = new Properties();
    int tenantId = ((UserRegistry) registry).getTenantId();

    if (trustedCertStores != null && trustedCertStores.length > 0) {
        StringBuilder trustString = new StringBuilder();
        for (String trustedCertStore : trustedCertStores) {
            if (trustString.length() > 0) {
                trustString.append(",");
            }
            trustString.append(trustedCertStore);
        }

        if (trustedCertStores.length != 0) {
            props.setProperty(ServerCrypto.PROP_ID_TRUST_STORES, trustString.toString());
        }
    }

    if (privateStore != null) {
        props.setProperty(ServerCrypto.PROP_ID_PRIVATE_STORE, privateStore);

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

        String privKeyAlias = KeyStoreUtil.getPrivateKeyAlias(ks);
        props.setProperty(ServerCrypto.PROP_ID_DEFAULT_ALIAS, privKeyAlias);
        props.setProperty(USER, privKeyAlias);
    }

    if (privateStore != null || (trustedCertStores != null && trustedCertStores.length > 0)) {
        //Set the tenant-ID in the properties
        props.setProperty(ServerCrypto.PROP_ID_TENANT_ID,
                Integer.toString(tenantId));
    }
    return props;
}
 
Example 13
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private Key getPrivateKey(String tenantDomain, int tenantId) throws IdentityOAuth2Exception {

        if (tenantDomain == null) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }

        if (tenantId == 0) {
            tenantId = OAuth2Util.getTenantId(tenantDomain);
        }

        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);
        }
        return privateKey;
    }
 
Example 14
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private Certificate getCertificate(String tenantDomain, int tenantId) throws Exception {

        if (tenantDomain == null) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }

        if (tenantId == 0) {
            tenantId = OAuth2Util.getTenantId(tenantDomain);
        }

        Certificate publicCert = null;

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

            KeyStore keyStore = null;
            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);
        }
        return publicCert;
    }
 
Example 15
Source File: AbstractAPIMgtGatewayJWTGenerator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public byte[] signJWT(String assertion) throws APIManagementException {

        try {
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
            PrivateKey privateKey = keyStoreManager.getDefaultPrivateKey();
            return APIUtil.signJwt(assertion, privateKey, signatureAlgorithm);
        } catch (Exception e) {
            throw new APIManagementException(e);
        }
    }
 
Example 16
Source File: AbstractAPIMgtGatewayJWTGenerator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to add public certificate to JWT_HEADER to signature verification.
 *
 * @throws APIManagementException
 */
protected String addCertToHeader() throws APIManagementException {

    try {
        KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
        Certificate publicCert = keyStoreManager.getDefaultPrimaryCertificate();
        return APIUtil.generateHeader(publicCert, signatureAlgorithm);
    } catch (Exception e) {
        String error = "Error in obtaining keystore";
        throw new APIManagementException(error, e);
    }
}
 
Example 17
Source File: CertificateMgtUtils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public Key getPrivateKey(String tenantDomain) throws RegistryException {
    //get tenantId
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);

    Key privateKey = null;

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

        if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            //derive key store name
            String ksName = tenantDomain.trim().replace('.', '-');
            String jksName = ksName + ".jks";
            //obtain private key
            //TODO: maintain a hash map with tenants' private keys after first initialization
            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);
    }
    return privateKey;
}
 
Example 18
Source File: ApiKeyGenerator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static byte[] buildSignature(String assertion) throws APIManagementException {
    PrivateKey privateKey;
    //get super tenant's key store manager
    KeyStoreManager tenantKSM = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
    try {
        privateKey = tenantKSM.getDefaultPrivateKey();
    } catch (Exception e) {
        throw new APIManagementException("Error while signing Api Key", e);
    }
    return APIUtil.signJwt(assertion, privateKey, "SHA256withRSA");
}
 
Example 19
Source File: Util.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * This method validates the signature of the SAML Response.
 * @param resp SAML Response
 * @return true, if signature is valid.
 */
public static boolean validateSignature(Response resp, String keyStoreName,
                                        String keyStorePassword, String alias, int tenantId,
                                        String tenantDomain) {
    boolean isSigValid = false;
    try {
        KeyStore keyStore = null;
        java.security.cert.X509Certificate cert = null;
        if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
            // get an instance of the corresponding Key Store Manager instance
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(tenantDomain);
        } else {
            keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(new File(keyStoreName)), keyStorePassword.toCharArray());
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(alias);
        }
        if(log.isDebugEnabled()){
            log.debug("Validating against "+cert.getSubjectDN().getName());
        }
        X509CredentialImpl credentialImpl = new X509CredentialImpl(cert);
        SignatureValidator signatureValidator = new SignatureValidator(credentialImpl);
        signatureValidator.validate(resp.getSignature());
        isSigValid = true;
        return isSigValid;
    } catch (Exception e) {
        if (log.isDebugEnabled()){
        log.debug("Signature verification is failed for "+tenantDomain);
        }
        return isSigValid;
    }
}