org.wso2.carbon.core.util.CryptoException Java Examples

The following examples show how to use org.wso2.carbon.core.util.CryptoException. 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: TaskUtils.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private static void secureLoadElement(Element element) throws CryptoException {
    Attr secureAttr = element.getAttributeNodeNS(SECURE_VAULT_NS, SECRET_ALIAS_ATTR_NAME);
    if (secureAttr != null) {
        element.setTextContent(loadFromSecureVault(secureAttr.getValue()));
        element.removeAttributeNode(secureAttr);
    }
    NodeList childNodes = element.getChildNodes();
    int count = childNodes.getLength();
    Node tmpNode;
    for (int i = 0; i < count; i++) {
        tmpNode = childNodes.item(i);
        if (tmpNode instanceof Element) {
            secureLoadElement((Element) tmpNode);
        }
    }
}
 
Example #2
Source File: RegistryDataManager.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Method to migrate encrypted password of SYSLOG_PROPERTIES registry resource
 *
 * @param migrateActiveTenantsOnly
 * @throws UserStoreException user store exception
 */
public void migrateSysLogPropertyPassword(boolean migrateActiveTenantsOnly)
        throws UserStoreException, RegistryException, CryptoException {
    try {
        //migrating super tenant configurations
        migrateSysLogPropertyPasswordForTenant(SUPER_TENANT_ID);
        log.info("Sys log property password migrated for tenant : " + SUPER_TENANT_DOMAIN_NAME);
    } catch (Exception e) {
        log.error("Error while migrating Sys log property password for tenant : " + SUPER_TENANT_DOMAIN_NAME, e);
    }
    Tenant[] tenants = MigrationServiceDataHolder.getRealmService().getTenantManager().getAllTenants();
    for (Tenant tenant : tenants) {
        if (migrateActiveTenantsOnly && !tenant.isActive()) {
            log.info("Tenant " + tenant.getDomain() + " is inactive. Skipping SYSLOG_PROPERTIES file migration. ");
            continue;
        }
        try {
            migrateSysLogPropertyPasswordForTenant(tenant.getId());
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
 
Example #3
Source File: RegistryDataManager.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypt the registry properties by new algorithm and update
 *
 * @param registry
 * @param resource
 * @param properties
 * @throws RegistryException
 * @throws CryptoException
 */
private void updateRegistryProperties(Registry registry, String resource, List<String> properties)
        throws RegistryException, CryptoException {
    if (registry == null || StringUtils.isEmpty(resource) || CollectionUtils.isEmpty(properties)) {
        return;
    }
    if (registry.resourceExists(resource)) {
        try {
            registry.beginTransaction();
            Resource resourceObj = registry.get(resource);
            for (String encryptedPropertyName : properties) {
                String oldValue = resourceObj.getProperty(encryptedPropertyName);
                String newValue = Utility.getNewEncryptedValue(oldValue);
                if (StringUtils.isNotEmpty(newValue)) {
                    resourceObj.setProperty(encryptedPropertyName, newValue);
                }
            }
            registry.put(resource, resourceObj);
            registry.commitTransaction();
        } catch (RegistryException e) {
            registry.rollbackTransaction();
            log.error("Unable to update the registry resource", e);
            throw e;
        }
    }
}
 
Example #4
Source File: DatasourceMigrator.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Migrate the password in datasource configuration
 *
 * @param tenantId
 * @param dataSources
 * @throws MigrationClientException
 */
private void updatePasswordInRegistryDataSources(int tenantId, List<Resource> dataSources)
        throws MigrationClientException {
    for (Resource dataSource : dataSources) {
        try {
            InputStream contentStream = dataSource.getContentStream();
            OMElement omElement = Utility.toOM(contentStream);
            Iterator pit = ((OMElement) ((OMElement) omElement.getChildrenWithName(Constant.DEFINITION_Q).next())
                    .getChildrenWithName(Constant.CONFIGURATION_Q).next()).getChildrenWithName(Constant.PASSWORD_Q);
            while (pit.hasNext()) {
                OMElement passwordElement = (OMElement) pit.next();
                if (Boolean.parseBoolean(passwordElement.getAttributeValue(Constant.ENCRYPTED_Q))) {
                    String password = passwordElement.getText();
                    String newEncryptedPassword = Utility.getNewEncryptedValue(password);
                    if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                        passwordElement.setText(newEncryptedPassword);
                        dataSource.setContent(omElement.toString().getBytes());
                        DataSourceDAO.saveDataSource(tenantId, dataSource);
                    }
                }
            }
        } catch (XMLStreamException | CryptoException | RegistryException | DataSourceException e) {
            throw new MigrationClientException(e.getMessage());
        }
    }
}
 
Example #5
Source File: EntitlementMediatorMigrator.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Iterate and change the password by new algorithm
 *
 * @param it
 * @throws MigrationClientException
 */
private void loopAndEncrypt(Iterator it) throws MigrationClientException {
    while (it.hasNext()) {
        OMElement element = (OMElement) it.next();
        if (element.getAttributeValue(Constant.REMOTE_SERVICE_PASSWORD_Q) != null
                && element.getAttributeValue(Constant.REMOTE_SERVICE_PASSWORD_Q)
                .startsWith(Constant.EM_ENCRYPTED_PASSWORD_PREFIX)) {
            String remoteServicePassword = element.getAttributeValue(Constant.REMOTE_SERVICE_PASSWORD_Q);
            String newEncryptedPassword;
            try {
                newEncryptedPassword = Utility.getNewEncryptedValue(
                        remoteServicePassword.replace(Constant.EM_ENCRYPTED_PASSWORD_PREFIX, ""));
                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                    element.getAttribute(Constant.REMOTE_SERVICE_PASSWORD_Q)
                            .setAttributeValue(Constant.EM_ENCRYPTED_PASSWORD_PREFIX + newEncryptedPassword);
                    isModified = true;
                }
            } catch (CryptoException e) {
                throw new MigrationClientException(e.getMessage());
            }
        } else if (element.getChildElements().hasNext()) {
            loopAndEncrypt(element.getChildElements());
        }
    }
}
 
Example #6
Source File: SecurityConfigAdmin.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private KerberosConfigData readKerberosConfigurations(OMElement carbonSecConfig) throws SecurityConfigException {

        KerberosConfigData kerberosConfigData = null;
        if (carbonSecConfig != null) {
            if (log.isDebugEnabled()) {
                log.debug("Reading kerberos configurations from carbonSecConfig : " + carbonSecConfig.toString());
            }
            OMElement kerberosElement = carbonSecConfig.getFirstChildWithName(new QName(SecurityConstants
                    .SECURITY_NAMESPACE, SecurityConstants.KERBEROS));
            if (kerberosElement != null) {
                kerberosConfigData = new KerberosConfigData();
                Map<String, String> kerberosProperties = getProperties(kerberosElement);
                if (kerberosProperties.get(KerberosConfig.SERVICE_PRINCIPLE_NAME) != null) {
                    kerberosConfigData.setServicePrincipleName(kerberosProperties.get(KerberosConfig
                            .SERVICE_PRINCIPLE_NAME));
                }
                if (kerberosProperties.get(KerberosConfig.SERVICE_PRINCIPLE_PASSWORD) != null) {
                    String encryptedString = kerberosProperties.get(KerberosConfig.SERVICE_PRINCIPLE_PASSWORD);
                    CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
                    try {
                        kerberosConfigData.setServicePrinciplePassword
                                (new String(cryptoUtil.base64DecodeAndDecrypt(encryptedString)));
                    } catch (CryptoException e) {
                        String msg = "Unable to decode and decrypt password string.";
                        log.warn(msg, e);
                    }
                }
            }
        }

        return kerberosConfigData;
    }
 
Example #7
Source File: PolicyPublisher.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void populateProperties(PublisherDataHolder holder,
                                PublisherDataHolder oldHolder, Resource resource) {

    PublisherPropertyDTO[] propertyDTOs = holder.getPropertyDTOs();
    for (PublisherPropertyDTO dto : propertyDTOs) {
        if (dto.getId() != null && dto.getValue() != null && dto.getValue().trim().length() > 0) {
            ArrayList<String> list = new ArrayList<String>();
            if (dto.isSecret()) {
                PublisherPropertyDTO propertyDTO = null;
                if (oldHolder != null) {
                    propertyDTO = oldHolder.getPropertyDTO(dto.getId());
                }
                if (propertyDTO == null || !propertyDTO.getValue().equalsIgnoreCase(dto.getValue())) {
                    try {
                        String encryptedValue = CryptoUtil.getDefaultCryptoUtil().
                                encryptAndBase64Encode(dto.getValue().getBytes());
                        dto.setValue(encryptedValue);
                    } catch (CryptoException e) {
                        log.error("Error while encrypting secret value of subscriber. " +
                                "Secret would not be persist.", e);
                        continue;
                    }
                }
            }
            list.add(dto.getValue());
            list.add(dto.getDisplayName());
            list.add(Integer.toString(dto.getDisplayOrder()));
            list.add(Boolean.toString(dto.isRequired()));
            list.add(Boolean.toString(dto.isSecret()));
            resource.setProperty(dto.getId(), list);
        }
    }
    resource.setProperty(PublisherDataHolder.MODULE_NAME, holder.getModuleName());
}
 
Example #8
Source File: SecurityConfigAdmin.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private String getEncryptedPassword(String password) throws SecurityConfigException {

        CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
        try {
            return cryptoUtil.encryptAndBase64Encode(password.getBytes());
        } catch (CryptoException e) {
            String msg = "Unable to encrypt and encode password string.";
            log.error(msg, e);
            throw new SecurityConfigException(msg, e);
        }
    }
 
Example #9
Source File: ServicePasswordCallbackHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private String getDecryptedPassword(String encryptedString) throws SecurityConfigException {
    CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
    try {
        return new String(cryptoUtil.base64DecodeAndDecrypt(encryptedString));
    } catch (CryptoException e) {
        String msg = "Unable to decode and decrypt password string.";
        log.error(msg, e);
        throw new SecurityConfigException(msg, e);
    }
}
 
Example #10
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getPreprocessedClientSecret(String processedClientSecret) throws IdentityOAuth2Exception {
    try {
        return decrypt(processedClientSecret);
    } catch (CryptoException e) {
        throw new IdentityOAuth2Exception("Error while retrieving preprocessed client secret", e);
    }
}
 
Example #11
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getProcessedClientSecret(String clientSecret) throws IdentityOAuth2Exception {
    try {
        return encrypt(clientSecret);
    } catch (CryptoException e) {
        throw new IdentityOAuth2Exception("Error while retrieving processed client secret", e);
    }
}
 
Example #12
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getPreprocessedAuthzCode(String processedAuthzCode) throws IdentityOAuth2Exception {
    try {
        return decrypt(processedAuthzCode);
    } catch (CryptoException e) {
        throw new IdentityOAuth2Exception("Error while retrieving preprocessed authorization code", e);
    }
}
 
Example #13
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getProcessedAuthzCode(String authzCode) throws IdentityOAuth2Exception {
    try {
        return encrypt(authzCode);
    } catch (CryptoException e) {
        throw new IdentityOAuth2Exception("Error while retrieving processed authorization code", e);
    }
}
 
Example #14
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getPreprocessedAccessTokenIdentifier(String processedAccessTokenIdentifier)
        throws IdentityOAuth2Exception {
    try {
        return decrypt(processedAccessTokenIdentifier);
    } catch (CryptoException e) {
        throw new IdentityOAuth2Exception("Error while retrieving preprocessed access token identifier", e);
    }
}
 
Example #15
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getProcessedAccessTokenIdentifier(String accessTokenIdentifier)
        throws IdentityOAuth2Exception {
    try {
        return encrypt(accessTokenIdentifier);
    } catch (CryptoException e) {
        throw new IdentityOAuth2Exception("Error while retrieving processed access token identifier", e);
    }
}
 
Example #16
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getPreprocessedRefreshToken(String processedRefreshToken)
        throws IdentityOAuth2Exception {
    try {
        return decrypt(processedRefreshToken);
    } catch (CryptoException e) {
        throw new IdentityOAuth2Exception("Error while retrieving preprocessed refresh token", e);
    }
}
 
Example #17
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getProcessedRefreshToken(String refreshToken)
        throws IdentityOAuth2Exception {
    try {
        return encrypt(refreshToken);
    } catch (CryptoException e) {
        throw new IdentityOAuth2Exception("Error while retrieving processed refresh token", e);
    }
}
 
Example #18
Source File: TaskUtils.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public static void secureResolveDocument(Document doc) throws TaskException {
    Element element = doc.getDocumentElement();
    if (element != null) {
        try {
            secureLoadElement(element);
        } catch (CryptoException e) {
            throw new TaskException("Error in secure load of document: " + e.getMessage(),
                    Code.UNKNOWN, e);
        }
    }
}
 
Example #19
Source File: RegistryDataManager.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Migrate keystore password in super tenant and other tenants
 *
 * @param tenantId
 * @throws RegistryException
 * @throws CryptoException
 */
private void migrateKeyStorePasswordForTenant(int tenantId) throws RegistryException, CryptoException {
    Registry registry = MigrationServiceDataHolder.getRegistryService().getGovernanceSystemRegistry(tenantId);
    if (registry.resourceExists(Constant.KEYSTORE_RESOURCE_PATH)) {
        Collection keyStoreCollection = (Collection) registry.get(Constant.KEYSTORE_RESOURCE_PATH);
        for (String keyStorePath : keyStoreCollection.getChildren()) {
            updateRegistryProperties(registry, keyStorePath,
                    new ArrayList<>(Arrays.asList(Constant.PASSWORD, Constant.PRIVATE_KEY_PASS)));
        }
    }
}
 
Example #20
Source File: PolicyPublisher.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void populateProperties(PublisherDataHolder holder,
                                PublisherDataHolder oldHolder, Resource resource) {

    PublisherPropertyDTO[] propertyDTOs = holder.getPropertyDTOs();
    for (PublisherPropertyDTO dto : propertyDTOs) {
        if (dto.getId() != null && dto.getValue() != null && dto.getValue().trim().length() > 0) {
            ArrayList<String> list = new ArrayList<String>();
            if (dto.isSecret()) {
                PublisherPropertyDTO propertyDTO = null;
                if (oldHolder != null) {
                    propertyDTO = oldHolder.getPropertyDTO(dto.getId());
                }
                if (propertyDTO == null || !propertyDTO.getValue().equalsIgnoreCase(dto.getValue())) {
                    try {
                        String encryptedValue = CryptoUtil.getDefaultCryptoUtil().
                                encryptAndBase64Encode(dto.getValue().getBytes());
                        dto.setValue(encryptedValue);
                    } catch (CryptoException e) {
                        log.error("Error while encrypting secret value of subscriber. " +
                                "Secret would not be persist.", e);
                        continue;
                    }
                }
            }
            list.add(dto.getValue());
            list.add(dto.getDisplayName());
            list.add(Integer.toString(dto.getDisplayOrder()));
            list.add(Boolean.toString(dto.isRequired()));
            list.add(Boolean.toString(dto.isSecret()));
            resource.setProperty(dto.getId(), list);
        }
    }
    resource.setProperty(PublisherDataHolder.MODULE_NAME, holder.getModuleName());
}
 
Example #21
Source File: SecondaryUserStoreConfigurator.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypt a given text.
 *
 * @param plainText Cipher text to be encrypted
 * @return Returns the encrypted text
 * @throws IdentityUserStoreMgtException Encryption failed
 */
public String encryptPlainText(String plainText) throws IdentityUserStoreMgtException {

    boolean isInternalKeyStoreEncryptionEnabled = false;
    boolean isSymmetricKeyEncryptionEnabled = false;
    ServerConfigurationService config =
            UserStoreConfigComponent.getServerConfigurationService();
    if (config != null) {
        String encryptionKeyStore = config.getFirstProperty(ENCRYPTION_KEYSTORE);

        if (INTERNAL_KEYSTORE.equalsIgnoreCase(encryptionKeyStore)) {
            isInternalKeyStoreEncryptionEnabled = true;
        }
        String cryptoProvider = config.getFirstProperty(CRYPTO_PROVIDER);
        if (SYMMETRIC_KEY_CRYPTO_PROVIDER.equalsIgnoreCase(cryptoProvider)) {
            isSymmetricKeyEncryptionEnabled = true;
        }
    }

    if (isInternalKeyStoreEncryptionEnabled && isSymmetricKeyEncryptionEnabled) {

        throw new IdentityUserStoreMgtException(String.format("Userstore encryption can not be supported due to " +
                "conflicting configurations: '%s' and '%s'. When using internal keystore, assymetric crypto " +
                "provider should be used.", INTERNAL_KEYSTORE, SYMMETRIC_KEY_CRYPTO_PROVIDER));
    } else if (isInternalKeyStoreEncryptionEnabled || isSymmetricKeyEncryptionEnabled) {

        try {
            return CryptoUtil.getDefaultCryptoUtil().encryptAndBase64Encode(plainText.getBytes());
        } catch (CryptoException e) {
            String errorMessage = "Error while encrypting the plain text using internal keystore.";
            throw new IdentityUserStoreMgtException(errorMessage, e);
        }
    } else {
        return encryptWithPrimaryKeyStore(config, plainText);
    }
}
 
Example #22
Source File: UserStoreUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Util function to encrypt given plain text using given cipher
 *
 * @param plainTextBytes target plain text to encrypt using the cipher
 * @return Cipher text
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 * @throws IOException
 */
public static byte[] encrypt(byte[] plainTextBytes) throws CryptoException {

    boolean isInternalKeyStoreEncryptionEnabled = false;
    boolean isSymmetricKeyEncryptionEnabled = false;
    ServerConfigurationService config =
            UserStoreConfigComponent.getServerConfigurationService();
    if (config != null) {
        String encryptionKeyStore = config.getFirstProperty(UserStoreConfigurationConstants.ENCRYPTION_KEYSTORE);

        if (INTERNAL_KEYSTORE.equalsIgnoreCase(encryptionKeyStore)) {
            isInternalKeyStoreEncryptionEnabled = true;
        }
        String cryptoProvider = config.getFirstProperty(UserStoreConfigurationConstants.CRYPTO_PROVIDER);
        if (UserStoreConfigurationConstants.SYMMETRIC_KEY_CRYPTO_PROVIDER.equalsIgnoreCase(cryptoProvider)) {
            isSymmetricKeyEncryptionEnabled = true;
        }
    }

    if (isInternalKeyStoreEncryptionEnabled && isSymmetricKeyEncryptionEnabled) {

        throw new CryptoException(String.format("Userstore encryption can not be supported due to " +
                        "conflicting configurations: '%s' and '%s'. When using internal keystore, assymetric crypto " +
                        "provider should be used.", UserStoreConfigurationConstants.INTERNAL_KEYSTORE,
                UserStoreConfigurationConstants.SYMMETRIC_KEY_CRYPTO_PROVIDER));
    } else if (isInternalKeyStoreEncryptionEnabled || isSymmetricKeyEncryptionEnabled) {
        return CryptoUtil.getDefaultCryptoUtil().encrypt(plainTextBytes);
    } else {
        return encryptWithPrimaryKeyStore(plainTextBytes);
    }
}
 
Example #23
Source File: UserStoreConfigurationDeployer.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypts the secondary user store configuration
 *
 * @param secondaryStoreDocument OMElement of respective file path
 * @throws UserStoreConfigurationDeployerException If update operation failed
 */
private void updateSecondaryUserStore(OMElement secondaryStoreDocument) throws
        UserStoreConfigurationDeployerException {
    String className = secondaryStoreDocument.getAttributeValue(new QName(UserStoreConfigurationConstants.PROPERTY_CLASS));
    ArrayList<String> encryptList = getEncryptPropertyList(className);
    Iterator<?> ite = secondaryStoreDocument.getChildrenWithName(new QName(UserStoreConfigurationConstants.PROPERTY));
    while (ite.hasNext()) {
        OMElement propElem = (OMElement) ite.next();

        if (propElem != null && (propElem.getText() != null)) {
            String propertyName = propElem.getAttributeValue(new QName(UserStoreConfigurationConstants.PROPERTY_NAME));

            OMAttribute encryptedAttr = propElem.getAttribute(new QName(UserStoreConfigurationConstants
                    .PROPERTY_ENCRYPTED));
            if (encryptedAttr == null) {
                boolean encrypt = encryptList.contains(propertyName) || isEligibleTobeEncrypted(propElem);
                if (encrypt) {
                    OMAttribute encryptAttr = propElem.getAttribute(new QName(UserStoreConfigurationConstants.PROPERTY_ENCRYPT));
                    if (encryptAttr != null) {
                        propElem.removeAttribute(encryptAttr);
                    }

                    try {
                        String cipherText = Base64.encode(UserStoreUtil.encrypt((propElem.getText().getBytes())));
                        propElem.setText(cipherText);
                        propElem.addAttribute(UserStoreConfigurationConstants.PROPERTY_ENCRYPTED, "true", null);
                    } catch (CryptoException e) {
                        String errMsg = "Encryption in secondary user store failed";
                        throw new UserStoreConfigurationDeployerException(errMsg, e);
                    }
                }
            }
        }
    }
}
 
Example #24
Source File: JMXProfileDataMigrator.java    From product-ei with Apache License 2.0 5 votes vote down vote up
private void reEncryptProfileWithNewCipher(Profile profile) throws MigrationClientException, CryptoException,
        RegistryException {
    String reEncryptedValue = Utility.getNewEncryptedValue(profile.getPass());
    if (StringUtils.isNotEmpty(reEncryptedValue)) {
        profile.setPass(reEncryptedValue);
        saveUpdatedProfile(profile);
    }
}
 
Example #25
Source File: Utility.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public static String getNewEncryptedValue(String encryptedValue) throws CryptoException {
    CryptoUtil cryptoUtil = getDefaultCryptoUtil();
    if (StringUtils.isNotEmpty(encryptedValue) && !isNewlyEncrypted(cryptoUtil, encryptedValue)
            && isEncryptedByRSA(cryptoUtil, encryptedValue)) {
        byte[] decryptedPassword = cryptoUtil.base64DecodeAndDecrypt(encryptedValue, Constant.RSA);
        return cryptoUtil.encryptAndBase64Encode(decryptedPassword);
    }
    return null;
}
 
Example #26
Source File: RegistryDataManager.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Encrypt the security policy password by new algorithm and update
 *
 * @param tenantId
 * @throws RegistryException
 * @throws CryptoException
 * @throws XMLStreamException
 */
private void updateSecurityPolicyPassword(int tenantId) throws RegistryException, CryptoException,
        XMLStreamException {
    InputStream resourceContent = null;
    XMLStreamReader parser = null;
    try {
        Registry registry = MigrationServiceDataHolder.getRegistryService().getConfigSystemRegistry(tenantId);
        List<String> policyPaths = getSTSPolicyPaths(registry);
        String newEncryptedPassword = null;
        for (String resourcePath : policyPaths) {
            if (registry.resourceExists(resourcePath)) {
                Resource resource = registry.get(resourcePath);
                resourceContent = resource.getContentStream();
                parser = XMLInputFactory.newInstance().createXMLStreamReader(resourceContent);
                StAXOMBuilder builder = new StAXOMBuilder(parser);
                OMElement documentElement = builder.getDocumentElement();
                Iterator it = documentElement.getChildrenWithName(new QName(Constant.CARBON_SEC_CONFIG));

                while (it != null && it.hasNext()) {
                    OMElement secConfig = (OMElement) it.next();
                    Iterator kerberosProperties = secConfig.getChildrenWithName(new QName(Constant.KERBEROS));
                    Iterator propertySet = null;
                    if ((kerberosProperties != null && kerberosProperties.hasNext())) {
                        propertySet = ((OMElement) kerberosProperties.next()).getChildElements();
                    }
                    if (propertySet != null) {
                        while (propertySet.hasNext()) {
                            OMElement kbProperty = (OMElement) propertySet.next();
                            if (Constant.SERVICE_PRINCIPAL_PASSWORD
                                    .equals(kbProperty.getAttributeValue(Constant.NAME_Q))) {
                                String encryptedPassword = kbProperty.getText();
                                newEncryptedPassword = Utility.getNewEncryptedValue(encryptedPassword);
                                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                                    kbProperty.setText(newEncryptedPassword);
                                }
                            }
                        }
                    }
                }
                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                    resource.setContent(RegistryUtils.encodeString(documentElement.toString()));
                    registry.beginTransaction();
                    registry.put(resourcePath, resource);
                    registry.commitTransaction();
                }
            }
        }
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (resourceContent != null) {
                try {
                    resourceContent.close();
                } catch (IOException e) {
                    log.error("Error occurred while closing Input stream", e);
                }
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }
    }

}
 
Example #27
Source File: RegistryDataManager.java    From product-ei with Apache License 2.0 4 votes vote down vote up
private void migrateSysLogPropertyPasswordForTenant(int tenantId) throws RegistryException, CryptoException {
    Registry registry = MigrationServiceDataHolder.getRegistryService().getConfigSystemRegistry(tenantId);
    updateRegistryProperties(registry, Constant.SYSLOG, new ArrayList<>(Arrays.asList(Constant.PASSWORD)));
}
 
Example #28
Source File: PublisherDataHolder.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public PublisherDataHolder(Resource resource, boolean returnSecrets) {
    List<PublisherPropertyDTO> propertyDTOs = new ArrayList<PublisherPropertyDTO>();
    if (resource != null && resource.getProperties() != null) {
        Properties properties = resource.getProperties();
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            PublisherPropertyDTO dto = new PublisherPropertyDTO();
            dto.setId((String) entry.getKey());
            Object value = entry.getValue();
            if (value instanceof ArrayList) {
                List list = (ArrayList) entry.getValue();
                if (list != null && list.size() > 0 && list.get(0) != null) {
                    dto.setValue((String) list.get(0));

                    if (list.size() > 1 && list.get(1) != null) {
                        dto.setDisplayName((String) list.get(1));
                    }
                    if (list.size() > 2 && list.get(2) != null) {
                        dto.setDisplayOrder(Integer.parseInt((String) list.get(2)));
                    }
                    if (list.size() > 3 && list.get(3) != null) {
                        dto.setRequired(Boolean.parseBoolean((String) list.get(3)));
                    }
                    if (list.size() > 4 && list.get(4) != null) {
                        dto.setSecret(Boolean.parseBoolean((String) list.get(4)));
                    }

                    if (dto.isSecret()) {
                        if (returnSecrets) {
                            String password = dto.getValue();
                            try {
                                password = new String(CryptoUtil.getDefaultCryptoUtil().
                                        base64DecodeAndDecrypt(dto.getValue()));
                            } catch (CryptoException e) {
                                log.error(e);
                                // ignore
                            }
                            dto.setValue(password);
                        }
                    }
                }
            }
            if (MODULE_NAME.equals(dto.getId())) {
                moduleName = dto.getValue();
                continue;
            }

            propertyDTOs.add(dto);
        }
    }
    this.propertyDTOs = propertyDTOs.toArray(new PublisherPropertyDTO[propertyDTOs.size()]);
}
 
Example #29
Source File: Utility.java    From product-ei with Apache License 2.0 4 votes vote down vote up
public static boolean isNewlyEncrypted(CryptoUtil cryptoUtil, String encryptedValue) throws CryptoException {
    return cryptoUtil.base64DecodeAndIsSelfContainedCipherText(encryptedValue);
}
 
Example #30
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private String encrypt(String plainText) throws CryptoException {
    return  CryptoUtil.getDefaultCryptoUtil().encryptAndBase64Encode(
            plainText.getBytes(Charsets.UTF_8));
}