org.apache.axiom.om.util.Base64 Java Examples

The following examples show how to use org.apache.axiom.om.util.Base64. 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: KeyStoreAdminClient.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public void addKeyStore(byte[] content, String filename, String password, String provider,
                        String type, String pvtkspass) throws java.lang.Exception {

    try {
        String data = Base64.encode(content);
        AddKeyStore request = new AddKeyStore();
        request.setFileData(data);
        request.setFilename(filename);
        request.setPassword(password);
        request.setProvider(provider);
        request.setType(type);
        request.setPvtkeyPass(pvtkspass);
        stub.addKeyStore(request);
    } catch (java.lang.Exception e) {
        log.error("Error in adding keystore", e);
        throw e;
    }
}
 
Example #2
Source File: IdentityApplicationManagementUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Generate thumbprint of certificate
 *
 * @param encodedCert Base64 encoded certificate
 * @return Certificate thumbprint
 * @throws java.security.NoSuchAlgorithmException Unsupported hash algorithm
 */
public static String generateThumbPrint(String encodedCert) throws NoSuchAlgorithmException {

    if (encodedCert != null) {
        MessageDigest digestValue = null;
        digestValue = MessageDigest.getInstance("SHA-1");
        byte[] der = Base64.decode(encodedCert);
        digestValue.update(der);
        byte[] digestInBytes = digestValue.digest();
        String publicCertThumbprint = hexify(digestInBytes);
        return publicCertThumbprint;
    } else {
        String errorMsg = "Invalid encoded certificate: \'NULL\'";
        log.debug(errorMsg);
        throw new IllegalArgumentException(errorMsg);
    }
}
 
Example #3
Source File: LDAPServerStoreManager.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private String getPasswordToStore(String password, String passwordHashMethod)
        throws DirectoryServerManagerException {

    String passwordToStore = password;

    if (passwordHashMethod != null) {
        try {

            if (passwordHashMethod.equals(LDAPServerManagerConstants.PASSWORD_HASH_METHOD_PLAIN_TEXT)) {
                return passwordToStore;
            }

            MessageDigest messageDigest = MessageDigest.getInstance(passwordHashMethod);
            byte[] digestValue = messageDigest.digest(password.getBytes(StandardCharsets.UTF_8));
            passwordToStore = "{" + passwordHashMethod + "}" + Base64.encode(digestValue);

        } catch (NoSuchAlgorithmException e) {
            throw new DirectoryServerManagerException("Invalid hashMethod", e);
        }
    }

    return passwordToStore;
}
 
Example #4
Source File: IdentityApplicationManagementUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Generate thumbprint of certificate
 *
 * @param encodedCert Base64 encoded certificate
 * @return Certificate thumbprint
 * @throws java.security.NoSuchAlgorithmException Unsupported hash algorithm
 */
public static String generateThumbPrint(String encodedCert) throws NoSuchAlgorithmException {

    if (encodedCert != null) {
        MessageDigest digestValue = null;
        digestValue = MessageDigest.getInstance("SHA-1");
        byte[] der = Base64.decode(encodedCert);
        digestValue.update(der);
        byte[] digestInBytes = digestValue.digest();
        String publicCertThumbprint = hexify(digestInBytes);
        return publicCertThumbprint;
    } else {
        String errorMsg = "Invalid encoded certificate: \'NULL\'";
        log.debug(errorMsg);
        throw new IllegalArgumentException(errorMsg);
    }
}
 
Example #5
Source File: IdentityApplicationManagementUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param encodedCert
 * @return
 * @throws CertificateException
 */
public static CertData getCertData(String encodedCert) throws CertificateException {

    if (encodedCert != null) {
        byte[] bytes = Base64.decode(encodedCert);
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(bytes));
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");
        return fillCertData(cert, formatter);
    } else {
        String errorMsg = "Invalid encoded certificate: \'NULL\'";
        log.debug(errorMsg);
        throw new IllegalArgumentException(errorMsg);
    }
}
 
Example #6
Source File: LDAPServerStoreManager.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private String getPasswordToStore(String password, String passwordHashMethod)
        throws DirectoryServerManagerException {

    String passwordToStore = password;

    if (passwordHashMethod != null) {
        try {

            if (passwordHashMethod.equals(LDAPServerManagerConstants.PASSWORD_HASH_METHOD_PLAIN_TEXT)) {
                return passwordToStore;
            }

            MessageDigest messageDigest = MessageDigest.getInstance(passwordHashMethod);
            byte[] digestValue = messageDigest.digest(password.getBytes(StandardCharsets.UTF_8));
            passwordToStore = "{" + passwordHashMethod + "}" + Base64.encode(digestValue);

        } catch (NoSuchAlgorithmException e) {
            throw new DirectoryServerManagerException("Invalid hashMethod", e);
        }
    }

    return passwordToStore;
}
 
Example #7
Source File: ReadCertStoreSampleUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static PrivateKey getSamplePrivateKey() throws Exception {
    // Read in the key into a String
    StringBuilder pkcs8Lines = new StringBuilder();
    BufferedReader rdr = new BufferedReader(new StringReader(PRIVATE_KEY));
    String line;
    while ((line = rdr.readLine()) != null) {
        pkcs8Lines.append(line);
    }

    // Remove the "BEGIN" and "END" lines, as well as any whitespace

    String pkcs8Pem = pkcs8Lines.toString();
    pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
    pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
    pkcs8Pem = pkcs8Pem.replaceAll("\\s+", "");

    // Base64 decode the result

    byte[] pkcs8EncodedBytes = Base64.decode(pkcs8Pem);

    // extract the private key

    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(keySpec);
}
 
Example #8
Source File: KeyStoreAdminClient.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void addKeyStore(byte[] content, String filename, String password, String provider,
                        String type, String pvtkspass) throws java.lang.Exception {
    try {
        String data = Base64.encode(content);
        AddKeyStore request = new AddKeyStore();
        request.setFileData(data);
        request.setFilename(filename);
        request.setPassword(password);
        request.setProvider(provider);
        request.setType(type);
        request.setPvtkeyPass(pvtkspass);
        stub.addKeyStore(request);
    } catch (java.lang.Exception e) {
        log.error("Error in adding keystore", e);
        throw e;
    }
}
 
Example #9
Source File: KeyStoreAdmin.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private CertData fillCertData(X509Certificate cert, String alise, Format formatter)
        throws CertificateEncodingException {
    CertData certData = null;

    if (includeCert) {
        certData = new CertDataDetail();
    } else {
        certData = new CertData();
    }
    certData.setAlias(alise);
    certData.setSubjectDN(cert.getSubjectDN().getName());
    certData.setIssuerDN(cert.getIssuerDN().getName());
    certData.setSerialNumber(cert.getSerialNumber());
    certData.setVersion(cert.getVersion());
    certData.setNotAfter(formatter.format(cert.getNotAfter()));
    certData.setNotBefore(formatter.format(cert.getNotBefore()));
    certData.setPublicKey(Base64.encode(cert.getPublicKey().getEncoded()));

    if (includeCert) {
        ((CertDataDetail) certData).setCertificate(cert);
    }

    return certData;
}
 
Example #10
Source File: KeyStoreAdminClient.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public void addTrustStore(byte[] content, String filename, String password, String provider,
                          String type) {

    try {
        String data = Base64.encode(content);
        AddTrustStore request = new AddTrustStore();

        request.setFileData(data);
        request.setFilename(filename);
        request.setPassword(password);
        request.setProvider(provider);
        request.setType(type);
        stub.addTrustStore(request);
    } catch (java.lang.Exception e) {
        log.error("Error in adding truststore", e);
    }
}
 
Example #11
Source File: Util.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static String preparePassword(String password, String saltValue) throws UserStoreException {
    try {
        String digestInput = password;
        if (saltValue != null) {
            digestInput = password + saltValue;
        }
        String digsestFunction = Util.getRealmConfig().getUserStoreProperties()
                .get(JDBCRealmConstants.DIGEST_FUNCTION);
        if (digsestFunction != null) {

            if (digsestFunction.equals(UserCoreConstants.RealmConfig.PASSWORD_HASH_METHOD_PLAIN_TEXT)) {
                return password;
            }

            MessageDigest dgst = MessageDigest.getInstance(digsestFunction);
            byte[] byteValue = dgst.digest(digestInput.getBytes(Charset.forName("UTF-8")));
            password = Base64.encode(byteValue);
        }
        return password;
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    }
}
 
Example #12
Source File: Util.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static String getSaltValue() {
    String saltValue = null;
    if ("true".equals(realmConfig.getUserStoreProperties().get(JDBCRealmConstants.STORE_SALTED_PASSWORDS))) {
        try {
            SecureRandom secureRandom = SecureRandom.getInstance(SHA_1_PRNG);
            byte[] bytes = new byte[16];
            //secureRandom is automatically seeded by calling nextBytes
            secureRandom.nextBytes(bytes);
            saltValue = Base64.encode(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA1PRNG algorithm could not be found.", e);
        }

    }
    return saltValue;
}
 
Example #13
Source File: Util.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static String getSaltValue() {
    String saltValue = null;
    if ("true".equals(realmConfig.getUserStoreProperties().get(JDBCRealmConstants.STORE_SALTED_PASSWORDS))) {
        try {
            SecureRandom secureRandom = SecureRandom.getInstance(SHA_1_PRNG);
            byte[] bytes = new byte[16];
            //secureRandom is automatically seeded by calling nextBytes
            secureRandom.nextBytes(bytes);
            saltValue = Base64.encode(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA1PRNG algorithm could not be found.", e);
        }

    }
    return saltValue;
}
 
Example #14
Source File: Util.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static String preparePassword(String password, String saltValue) throws UserStoreException {
    try {
        String digestInput = password;
        if (saltValue != null) {
            digestInput = password + saltValue;
        }
        String digsestFunction = Util.getRealmConfig().getUserStoreProperties()
                .get(JDBCRealmConstants.DIGEST_FUNCTION);
        if (digsestFunction != null) {

            if (digsestFunction.equals(UserCoreConstants.RealmConfig.PASSWORD_HASH_METHOD_PLAIN_TEXT)) {
                return password;
            }

            MessageDigest dgst = MessageDigest.getInstance(digsestFunction);
            byte[] byteValue = dgst.digest(digestInput.getBytes(Charset.forName("UTF-8")));
            password = Base64.encode(byteValue);
        }
        return password;
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    }
}
 
Example #15
Source File: KeyStoreAdmin.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private CertData fillCertData(X509Certificate cert, String alise, Format formatter)
        throws CertificateEncodingException {
    CertData certData = null;

    if (includeCert) {
        certData = new CertDataDetail();
    } else {
        certData = new CertData();
    }
    certData.setAlias(alise);
    certData.setSubjectDN(cert.getSubjectDN().getName());
    certData.setIssuerDN(cert.getIssuerDN().getName());
    certData.setSerialNumber(cert.getSerialNumber());
    certData.setVersion(cert.getVersion());
    certData.setNotAfter(formatter.format(cert.getNotAfter()));
    certData.setNotBefore(formatter.format(cert.getNotBefore()));
    certData.setPublicKey(Base64.encode(cert.getPublicKey().getEncoded()));

    if (includeCert) {
        ((CertDataDetail) certData).setCertificate(cert);
    }

    return certData;
}
 
Example #16
Source File: Utils.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @param value
 * @return
 * @throws UserStoreException
 */
public static String doHash(String value) throws UserStoreException {
    try {
        String digsestFunction = "SHA-256";
        MessageDigest dgst = MessageDigest.getInstance(digsestFunction);
        byte[] byteValue = dgst.digest(value.getBytes());
        return Base64.encode(byteValue);
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    }
}
 
Example #17
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 #18
Source File: IdPManagementUIUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private static String handleCertificateDeletion(String oldCertificateValues, String deletedCertificateValues) {

        String decodedOldCertificate = new String(Base64.decode(oldCertificateValues), StandardCharsets.UTF_8);
        String decodedDeletedCertificate = new String(Base64.decode(deletedCertificateValues), StandardCharsets.UTF_8);

        Set<String> updatedCertificateSet = new LinkedHashSet<>(getExtractedCertificateValues(decodedOldCertificate));
        updatedCertificateSet.removeAll(getExtractedCertificateValues(decodedDeletedCertificate));
        return Base64.encode(String.join("", updatedCertificateSet).getBytes(StandardCharsets.UTF_8));
    }
 
Example #19
Source File: IdPManagementUIUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private static String handleCertificateAddition(String oldCertValues, String newCertValues) {

        String decodedOldCertificate = new String(Base64.decode(oldCertValues), StandardCharsets.UTF_8);
        String decodedNewCertificate = new String(Base64.decode(newCertValues), StandardCharsets.UTF_8);

        Set<String> updatedCertificateSet = new LinkedHashSet<>(getExtractedCertificateValues
                (decodedOldCertificate));

        updatedCertificateSet.addAll(getExtractedCertificateValues(decodedNewCertificate));
        return Base64.encode(String.join("", updatedCertificateSet).getBytes(StandardCharsets.UTF_8));
    }
 
Example #20
Source File: JDBCUserStoreManager.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * @param password
 * @param saltValue
 * @return
 * @throws UserStoreException
 */
@Deprecated
protected String preparePassword(String password, String saltValue) throws UserStoreException {
    try {
        String digestInput = password;
        if (saltValue != null) {
            digestInput = password + saltValue;
        }
        String digsestFunction = realmConfig.getUserStoreProperties().get(
                JDBCRealmConstants.DIGEST_FUNCTION);
        if (digsestFunction != null) {

            if (digsestFunction
                    .equals(UserCoreConstants.RealmConfig.PASSWORD_HASH_METHOD_PLAIN_TEXT)) {
                return password;
            }

            MessageDigest dgst = MessageDigest.getInstance(digsestFunction);
            byte[] byteValue = dgst.digest(digestInput.getBytes());
            password = Base64.encode(byteValue);
        }
        return password;
    } catch (NoSuchAlgorithmException e) {
        String msg = "Error occurred while preparing password.";
        if (log.isDebugEnabled()) {
            log.debug(msg, e);
        }
        throw new UserStoreException(msg, e);
    }
}
 
Example #21
Source File: OpenIDAssociationDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
     * Tries to store the association in the identity database. But if the entry
     * already exists this operation doesn't do anything useful.
     *
     * @param association
     */
    public void storeAssociation(Association association) {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;

        try {

//            if (!isAssociationExist(connection, association.getHandle())) {
                prepStmt = connection.prepareStatement(OpenIDSQLQueries.STORE_ASSOCIATION);
                prepStmt.setString(1, association.getHandle());
                prepStmt.setString(2, association.getType());
                prepStmt.setTimestamp(3, new java.sql.Timestamp(association.getExpiry().getTime()));
                prepStmt.setString(4, Base64.encode(association.getMacKey().getEncoded()));
                prepStmt.setString(5, associationStore);
                prepStmt.execute();
                connection.commit();
                if(log.isDebugEnabled()) {
                    log.debug("Association " + association.getHandle() + " successfully stored in the database");
                }
//            } else {
//                log.debug("Association " + association.getHandle() + " already exist in the database.");
//            }
            connection.commit();
        } catch (SQLException e) {
            log.error("Failed to store the association " + association.getHandle(), e);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }
 
Example #22
Source File: IdentityApplicationManagementUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Generate thumbprint of certificate
 *
 * @param encodedCert Base64 encoded certificate
 * @return Decoded <code>Certificate</code>
 * @throws java.security.cert.CertificateException Error when decoding certificate
 */
public static Certificate decodeCertificate(String encodedCert) throws CertificateException {

    if (encodedCert != null) {
        byte[] bytes = Base64.decode(encodedCert);
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(bytes));
        return cert;
    } else {
        String errorMsg = "Invalid encoded certificate: \'NULL\'";
        log.debug(errorMsg);
        throw new IllegalArgumentException(errorMsg);
    }
}
 
Example #23
Source File: IdentityApplicationManagementUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param cert
 * @param formatter
 * @return
 * @throws CertificateEncodingException
 */
private static CertData fillCertData(X509Certificate cert, Format formatter)
        throws CertificateEncodingException {

    CertData certData = new CertData();
    certData.setSubjectDN(cert.getSubjectDN().getName());
    certData.setIssuerDN(cert.getIssuerDN().getName());
    certData.setSerialNumber(cert.getSerialNumber());
    certData.setVersion(cert.getVersion());
    certData.setNotAfter(formatter.format(cert.getNotAfter()));
    certData.setNotBefore(formatter.format(cert.getNotBefore()));
    certData.setPublicKey(Base64.encode(cert.getPublicKey().getEncoded()));
    return certData;
}
 
Example #24
Source File: KeyStoreAdminClient.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void importCertToStore(String filename, byte[] content, String keyStoreName)
        throws java.lang.Exception {
    try {
        String data = Base64.encode(content);
        ImportCertToStore request = new ImportCertToStore();
        request.setFileName(filename);
        request.setFileData(data);
        request.setKeyStoreName(keyStoreName);
        stub.importCertToStore(request);
    } catch (java.lang.Exception e) {
        log.error("Error in importing cert to store.", e);
        throw e;
    }
}
 
Example #25
Source File: JsonMessageModule.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * To get Base64 encoded username:password for basic authentication header
 *
 * @param username username
 * @param password password
 * @return Base64 encoded value of username:password
 */
private String getBase64EncodedBasicAuthHeader(String username, String password) {

    String concatenatedCredential = username + ":" + password;
    byte[] byteValue = concatenatedCredential.getBytes(Charsets.UTF_8);
    String encodedAuthHeader = Base64.encode(byteValue);
    encodedAuthHeader = "Basic " + encodedAuthHeader;
    return encodedAuthHeader;
}
 
Example #26
Source File: Utils.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param value
 * @return
 * @throws UserStoreException
 */
public static String doHash(String value) throws UserStoreException {
    try {
        String digsestFunction = "SHA-256";
        MessageDigest dgst = MessageDigest.getInstance(digsestFunction);
        byte[] byteValue = dgst.digest(value.getBytes());
        return Base64.encode(byteValue);
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    }
}
 
Example #27
Source File: ApacheDirectoryPartitionManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void addAdminPassword(ServerEntry adminEntry, String password,
                              PasswordAlgorithm algorithm,
                              final boolean kdcEnabled)
        throws DirectoryServerException {

    try {
        String passwordToStore = "{" + algorithm.getAlgorithmName() + "}";
        if (algorithm != PasswordAlgorithm.PLAIN_TEXT && !kdcEnabled) {
            MessageDigest md = MessageDigest.getInstance(algorithm.getAlgorithmName());
            md.update(password.getBytes());
            byte[] bytes = md.digest();
            String hash = Base64.encode(bytes);
            passwordToStore = passwordToStore + hash;

        } else {

            if (kdcEnabled) {
                logger.warn(
                        "KDC enabled. Enforcing passwords to be plain text. Cause - KDC " +
                                "cannot operate with hashed passwords.");
            }

            passwordToStore = password;
        }

        adminEntry.put("userPassword", passwordToStore.getBytes());

    } catch (NoSuchAlgorithmException e) {
        throwDirectoryServerException("Could not find matching hash algorithm - " +
                algorithm.getAlgorithmName(), e);
    }

}
 
Example #28
Source File: SecondaryUserStoreConfigurationUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param plainText Cipher text to be encrypted
 * @return Returns the encrypted text
 * @throws IdentityUserStoreMgtException Encryption failed
 */
public static String encryptPlainText(String plainText) throws IdentityUserStoreMgtException {

    if (cipher == null) {
        initializeKeyStore();
    }

    try {
        return Base64.encode(cipher.doFinal((plainText.getBytes())));
    } catch (GeneralSecurityException e) {
        String errMsg = "Failed to generate the cipher text";
        throw new IdentityUserStoreMgtException(errMsg, e);
    }
}
 
Example #29
Source File: UserStoreConfigurationDeployer.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypts the secondary user store configuration
 *
 * @param secondaryStoreDocument OMElement of respective file path
 * @param cipher                 Cipher object read for super-tenant's key store
 * @throws UserStoreConfigurationDeployerException If update operation failed
 */
private void updateSecondaryUserStore(OMElement secondaryStoreDocument, Cipher cipher) 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(cipher.doFinal((propElem.getText().getBytes())));
                        propElem.setText(cipherText);
                        propElem.addAttribute(UserStoreConfigurationConstants.PROPERTY_ENCRYPTED, "true", null);
                    } catch (GeneralSecurityException e) {
                        String errMsg = "Encryption in secondary user store failed";
                        throw new UserStoreConfigurationDeployerException(errMsg, e);
                    }
                }
            }
        }
    }
}
 
Example #30
Source File: BasicAuthUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getBase64EncodedBasicAuthHeader(String userName, String password) {
    String concatenatedCredential = userName + ":" + password;
    byte[] byteValue = concatenatedCredential.getBytes();
    String encodedAuthHeader = Base64.encode(byteValue);
    encodedAuthHeader = "Basic " + encodedAuthHeader;
    return encodedAuthHeader;
}