diff --git a/src/main/java/com/iemr/common/config/encryption/SecurePassword.java b/src/main/java/com/iemr/common/config/encryption/SecurePassword.java index 18fdb935..15463b7a 100644 --- a/src/main/java/com/iemr/common/config/encryption/SecurePassword.java +++ b/src/main/java/com/iemr/common/config/encryption/SecurePassword.java @@ -27,7 +27,6 @@ import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; - import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; @@ -36,7 +35,7 @@ @Service public class SecurePassword { public String generateStrongPassword(String password) throws NoSuchAlgorithmException, InvalidKeySpecException { - int iterations = 1000; + int iterations = 1001; char[] chars = password.toCharArray(); byte[] salt = getSalt(); @@ -64,9 +63,68 @@ private String toHex(byte[] array) { return hex; } - + public int validatePassword(String originalPassword, String storedPassword) + throws NoSuchAlgorithmException, InvalidKeySpecException { + int validCount = 0; + String[] parts = storedPassword.split(":"); + int iterations = Integer.parseInt(parts[0]); + byte[] salt = fromHex(parts[1]); + byte[] hash = fromHex(parts[2]); + if (iterations == 1000) { + PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, 1000, hash.length * 8); + SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + byte[] testHash = skf.generateSecret(spec).getEncoded(); + int diff = hash.length ^ testHash.length; + for (int i = 0; (i < hash.length) && (i < testHash.length); i++) { + diff |= hash[i] ^ testHash[i]; + } + if (diff == 0) { + // return 1 if using SHA1 algorithm to execute save and login Operation + validCount = 1; + return validCount; + } else { + PBEKeySpec spec1 = new PBEKeySpec(originalPassword.toCharArray(), salt, iterations, hash.length * 8); + SecretKeyFactory skf1 = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); + byte[] testHash1 = skf1.generateSecret(spec1).getEncoded(); - public boolean validatePassword(String originalPassword, String storedPassword) + int diff1 = hash.length ^ testHash1.length; + for (int i = 0; (i < hash.length) && (i < testHash1.length); i++) { + diff1 |= hash[i] ^ testHash1[i]; + } + if (diff1 == 0) { + // return 2 if using SHA512 algorithm to execute login Operation + validCount = 2; + return validCount; + } else { + // return 0 if wrong password + validCount = 0; + return validCount; + } + } + } + if (iterations == 1001) { + + PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, iterations, hash.length * 8); + SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); + byte[] testHash = skf.generateSecret(spec).getEncoded(); + + int diff = hash.length ^ testHash.length; + for (int i = 0; (i < hash.length) && (i < testHash.length); i++) { + diff |= hash[i] ^ testHash[i]; + } + if (diff == 0) { + // return 3 if using SHA512 algorithm to execute login Operation + validCount = 3; + return validCount; + } else { + validCount = 0; + return validCount; + } + } + return validCount; + } + + public boolean validatePasswordExisting(String originalPassword, String storedPassword) throws NoSuchAlgorithmException, InvalidKeySpecException { String[] parts = storedPassword.split(":"); int iterations = Integer.parseInt(parts[0]); @@ -74,7 +132,7 @@ public boolean validatePassword(String originalPassword, String storedPassword) byte[] hash = fromHex(parts[2]); PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, iterations, hash.length * 8); - SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); + SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] testHash = skf.generateSecret(spec).getEncoded(); int diff = hash.length ^ testHash.length; diff --git a/src/main/java/com/iemr/common/controller/users/IEMRAdminController.java b/src/main/java/com/iemr/common/controller/users/IEMRAdminController.java index 78777a3c..073c5c5f 100644 --- a/src/main/java/com/iemr/common/controller/users/IEMRAdminController.java +++ b/src/main/java/com/iemr/common/controller/users/IEMRAdminController.java @@ -21,6 +21,8 @@ */ package com.iemr.common.controller.users; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -36,6 +38,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -334,33 +337,33 @@ public String superUserAuthenticate( return response.toString(); } - @CrossOrigin() - @ApiOperation(value = "User authentication V1") - @RequestMapping(value = "/userAuthenticateV1", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON) - public String userAuthenticateV1( - @ApiParam(value = "\"{\\\"userName\\\":\\\"String\\\",\\\"password\\\":\\\"String\\\"}\"") @RequestBody LoginRequestModel loginRequest, - HttpServletRequest request) { - OutputResponse response = new OutputResponse(); - logger.info("userAuthenticate request "); - try { - - String remoteAddress = request.getHeader("X-FORWARDED-FOR"); - if (remoteAddress == null || remoteAddress.trim().length() == 0) { - remoteAddress = request.getRemoteAddr(); - } - LoginResponseModel resp = iemrAdminUserServiceImpl.userAuthenticateV1(loginRequest, remoteAddress, - request.getRemoteHost()); - JSONObject responseObj = new JSONObject(OutputMapper.gsonWithoutExposeRestriction().toJson(resp)); - responseObj = iemrAdminUserServiceImpl.generateKeyAndValidateIP(responseObj, remoteAddress, - request.getRemoteHost()); - response.setResponse(responseObj.toString()); - } catch (Exception e) { - logger.error("userAuthenticate failed with error " + e.getMessage(), e); - response.setError(e); - } - logger.info("userAuthenticate response " + response.toString()); - return response.toString(); - } +// @CrossOrigin() +// @ApiOperation(value = "User authentication V1") +// @RequestMapping(value = "/userAuthenticateV1", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON) +// public String userAuthenticateV1( +// @ApiParam(value = "\"{\\\"userName\\\":\\\"String\\\",\\\"password\\\":\\\"String\\\"}\"") @RequestBody LoginRequestModel loginRequest, +// HttpServletRequest request) { +// OutputResponse response = new OutputResponse(); +// logger.info("userAuthenticate request "); +// try { +// +// String remoteAddress = request.getHeader("X-FORWARDED-FOR"); +// if (remoteAddress == null || remoteAddress.trim().length() == 0) { +// remoteAddress = request.getRemoteAddr(); +// } +// LoginResponseModel resp = iemrAdminUserServiceImpl.userAuthenticateV1(loginRequest, remoteAddress, +// request.getRemoteHost()); +// JSONObject responseObj = new JSONObject(OutputMapper.gsonWithoutExposeRestriction().toJson(resp)); +// responseObj = iemrAdminUserServiceImpl.generateKeyAndValidateIP(responseObj, remoteAddress, +// request.getRemoteHost()); +// response.setResponse(responseObj.toString()); +// } catch (Exception e) { +// logger.error("userAuthenticate failed with error " + e.getMessage(), e); +// response.setError(e); +// } +// logger.info("userAuthenticate response " + response.toString()); +// return response.toString(); +// } @CrossOrigin() @ApiOperation(value = "Get login response") @@ -472,15 +475,24 @@ public String changePassword( throw new IEMRException("Change password failed with error as user is not available"); } try { - if (!securePassword.validatePassword(changePassword.getPassword(), mUsers.get(0).getPassword())) { - throw new IEMRException("Change password failed with error as old password is incorrect"); + int validatePassword; + validatePassword = securePassword.validatePassword(changePassword.getPassword(), + mUsers.get(0).getPassword()); + if (validatePassword == 1) { + User mUser = mUsers.get(0); + noOfRowUpdated = iemrAdminUserServiceImpl.setForgetPassword(mUser, changePassword.getNewPassword(), + changePassword.getTransactionId(), changePassword.getIsAdmin()); + + } else if (validatePassword == 2) { + User mUser = mUsers.get(0); + noOfRowUpdated = iemrAdminUserServiceImpl.setForgetPassword(mUser, changePassword.getNewPassword(), + changePassword.getTransactionId(), changePassword.getIsAdmin()); + } } catch (Exception e) { - throw new IEMRException("Change password failed with error as old password is incorrect"); + throw new IEMRException(e.getMessage()); } - User mUser = mUsers.get(0); - noOfRowUpdated = iemrAdminUserServiceImpl.setForgetPassword(mUser, changePassword.getNewPassword(), - changePassword.getTransactionId(), changePassword.getIsAdmin()); + if (noOfRowUpdated > 0) { changeReqResult = "Password SuccessFully Change"; } else { @@ -859,4 +871,6 @@ public String validateSecurityQuestionAndAnswer( return response.toString(); } + + } diff --git a/src/main/java/com/iemr/common/repository/users/IEMRUserRepositoryCustom.java b/src/main/java/com/iemr/common/repository/users/IEMRUserRepositoryCustom.java index 2976c64d..d0802915 100644 --- a/src/main/java/com/iemr/common/repository/users/IEMRUserRepositoryCustom.java +++ b/src/main/java/com/iemr/common/repository/users/IEMRUserRepositoryCustom.java @@ -74,5 +74,8 @@ public interface IEMRUserRepositoryCustom extends CrudRepository { @Query("SELECT u FROM UserSecurityQMapping u WHERE u.UserID=:UserID AND u.QuestionID=:QuestionID AND u.Answers=:Answers") UserSecurityQMapping verifySecurityQuestionAnswers(@Param("UserID") Long UserID, @Param("QuestionID") String QuestionID, @Param("Answers") String Answers); + + @Query("SELECT u FROM User u WHERE u.userID=5718") + User getAllExistingUsers(); } diff --git a/src/main/java/com/iemr/common/service/users/IEMRAdminUserService.java b/src/main/java/com/iemr/common/service/users/IEMRAdminUserService.java index fd827f6c..c6cf704d 100644 --- a/src/main/java/com/iemr/common/service/users/IEMRAdminUserService.java +++ b/src/main/java/com/iemr/common/service/users/IEMRAdminUserService.java @@ -114,6 +114,8 @@ public List getUserServiceRoleMappingForProvider(Integ String generateTransactionIdForPasswordChange(User user) throws Exception; + + } diff --git a/src/main/java/com/iemr/common/service/users/IEMRAdminUserServiceImpl.java b/src/main/java/com/iemr/common/service/users/IEMRAdminUserServiceImpl.java index 7ee8ed6c..fe20da49 100644 --- a/src/main/java/com/iemr/common/service/users/IEMRAdminUserServiceImpl.java +++ b/src/main/java/com/iemr/common/service/users/IEMRAdminUserServiceImpl.java @@ -21,8 +21,11 @@ */ package com.iemr.common.service.users; +import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -33,6 +36,9 @@ import java.util.Set; import java.util.UUID; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; + import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -86,10 +92,10 @@ import com.iemr.common.repository.users.VanServicepointMappingRepo; import com.iemr.common.service.cti.CTIService; import com.iemr.common.utils.config.ConfigProperties; +import com.iemr.common.utils.encryption.AESUtil; import com.iemr.common.utils.exception.IEMRException; import com.iemr.common.utils.mapper.InputMapper; import com.iemr.common.utils.mapper.OutputMapper; -import com.iemr.common.utils.redis.RedisSessionException; import com.iemr.common.utils.response.OutputResponse; import com.iemr.common.utils.rsa.RSAUtil; import com.iemr.common.utils.sessionobject.SessionObject; @@ -113,6 +119,8 @@ public class IEMRAdminUserServiceImpl implements IEMRAdminUserService { @Autowired private RoleMapper roleMapper; + @Autowired + private AESUtil aesUtil; @Autowired private SessionObject sessionObject; @@ -227,7 +235,27 @@ else if (users.get(0).getStatusID() > 2) failedAttempt = 5; User user = users.get(0); try { - if (!securePassword.validatePassword(password, user.getPassword())) { + int validatePassword; + validatePassword = securePassword.validatePassword(password, user.getPassword()); + if (validatePassword == 1) { + int iterations = 1001; + char[] chars = password.toCharArray(); + byte[] salt = getSalt(); + + PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 512); + SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); + byte[] hash = skf.generateSecret(spec).getEncoded(); + String updatedPassword = iterations + ":" + toHex(salt) + ":" + toHex(hash); + // save operation + user.setPassword(updatedPassword); + iEMRUserRepositoryCustom.save(user); + + } else if (validatePassword == 2) { + iEMRUserRepositoryCustom.save(user); + + } else if (validatePassword == 3) { + iEMRUserRepositoryCustom.save(user); + } else if (validatePassword == 0) { if (user.getFailedAttempt() + 1 >= failedAttempt) { user.setFailedAttempt(user.getFailedAttempt() + 1); user.setDeleted(true); @@ -243,8 +271,6 @@ else if (users.get(0).getStatusID() > 2) + (ConfigProperties.getInteger("failedLoginAttempt") - user.getFailedAttempt()) + " more attempt left."); } - - // throw new IEMRException("User login failed due to incorrect username/password"); } else { if (user.getFailedAttempt() != 0) { user.setFailedAttempt(0); @@ -279,13 +305,61 @@ public User superUserAuthenticate(String userName, String password) throws Excep if (users.size() != 1) { throw new IEMRException("User login failed due to incorrect username/password"); + } else { + if (users.get(0).getDeleted()) + throw new IEMRException("Your account is locked or de-activated. Please contact administrator"); + else if (users.get(0).getStatusID() > 2) + throw new IEMRException("Your account is not active. Please contact administrator"); } + int failedAttempt = 0; + if (failedLoginAttempt != null) + failedAttempt = Integer.parseInt(failedLoginAttempt); + else + failedAttempt = 5; + User user = users.get(0); try { - if (!securePassword.validatePassword(password, users.get(0).getPassword())) { - throw new IEMRException("User login failed due to incorrect username/password"); + int validatePassword; + validatePassword = securePassword.validatePassword(password, user.getPassword()); + if (validatePassword == 1) { + int iterations = 1001; + char[] chars = password.toCharArray(); + byte[] salt = getSalt(); + + PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 512); + SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); + byte[] hash = skf.generateSecret(spec).getEncoded(); + String updatedPassword = iterations + ":" + toHex(salt) + ":" + toHex(hash); + // save operation + user.setPassword(updatedPassword); + iEMRUserRepositoryCustom.save(user); + + } else if (validatePassword == 2) { + iEMRUserRepositoryCustom.save(user); + + } else if (validatePassword == 0) { + if (user.getFailedAttempt() + 1 >= failedAttempt) { + user.setFailedAttempt(user.getFailedAttempt() + 1); + user.setDeleted(true); + user = iEMRUserRepositoryCustom.save(user); + throw new IEMRException( + "User login failed due to incorrect username/password. Your account is locked due to " + + ConfigProperties.getInteger("failedLoginAttempt") + + " failed attempts. Please contact administrator."); + } else { + user.setFailedAttempt(user.getFailedAttempt() + 1); + user = iEMRUserRepositoryCustom.save(user); + throw new IEMRException("User login failed due to incorrect username/password. " + + (ConfigProperties.getInteger("failedLoginAttempt") - user.getFailedAttempt()) + + " more attempt left."); + } + } else { + if (user.getFailedAttempt() != 0) { + user.setFailedAttempt(0); + user = iEMRUserRepositoryCustom.save(user); + } } } catch (Exception e) { - throw new IEMRException("User login failed due to incorrect username/password"); + throw new IEMRException(e.getMessage()); } return users.get(0); } @@ -298,7 +372,7 @@ public LoginResponseModel userAuthenticateV1(LoginRequestModel loginRequest, Str if (users.size() == 1) { User user = users.get(0); try { - if (!securePassword.validatePassword(loginRequest.getPassword(), user.getPassword())) { + if (!securePassword.validatePasswordExisting(loginRequest.getPassword(), user.getPassword())) { throw new IEMRException("User login failed due to incorrect username/password"); } } catch (Exception e) { @@ -350,30 +424,31 @@ public List userSecurityQuestion(Long userId) { } @Override - public int setForgetPassword(User user, String loginpass, String transactionId, Boolean isAdmin) throws IEMRException { + public int setForgetPassword(User user, String loginpass, String transactionId, Boolean isAdmin) + throws IEMRException { int count = 0; try { - if(isAdmin !=null && isAdmin == true) { - updateCTIPasswordForUserV1(user.getUserID(), loginpass); - loginpass = securePassword.generateStrongPassword(loginpass); - count = iEMRUserRepositoryCustom.updateSetForgetPassword(user.getUserID(), loginpass); - } else { - String tokenFromRedis = sessionObject - .getSessionObjectForChangePassword((user.getUserID().toString() + user.getUserName())); - if (tokenFromRedis.equalsIgnoreCase(transactionId)) { - + if (isAdmin != null && isAdmin == true) { updateCTIPasswordForUserV1(user.getUserID(), loginpass); loginpass = securePassword.generateStrongPassword(loginpass); count = iEMRUserRepositoryCustom.updateSetForgetPassword(user.getUserID(), loginpass); - // Deleting transaction Id - if (count > 0) - sessionObject.deleteSessionObject((user.getUserID().toString() + user.getUserName())); - else - throw new IEMRException("error while updating new password"); } else { - throw new IEMRException("Unable to fetch transaction Id or transaction Id is expired"); - } + String tokenFromRedis = sessionObject + .getSessionObjectForChangePassword((user.getUserID().toString() + user.getUserName())); + if (tokenFromRedis.equalsIgnoreCase(transactionId)) { + + updateCTIPasswordForUserV1(user.getUserID(), loginpass); + loginpass = securePassword.generateStrongPassword(loginpass); + count = iEMRUserRepositoryCustom.updateSetForgetPassword(user.getUserID(), loginpass); + // Deleting transaction Id + if (count > 0) + sessionObject.deleteSessionObject((user.getUserID().toString() + user.getUserName())); + else + throw new IEMRException("error while updating new password"); + } else { + throw new IEMRException("Unable to fetch transaction Id or transaction Id is expired"); + } } } catch (Exception e) { logger.error("Error while changing the password: " + e.getMessage(), e); @@ -798,14 +873,14 @@ public JSONObject generateKeyAndValidateIP(JSONObject responseObj, String ipAddr /** * SH20094090,19-04-2022 * - * @param responseObj,key - * @param key Function to set new session object whenever a user logs in + * @param responseObj,key + * @param key Function to set new session object whenever a user + * logs in */ public void setConcurrentCheckSessionObject(JSONObject responseObj, String key) { try { - if ((responseObj.get("userName")) != null && (responseObj.get("userName").toString()) != null) - { - logger.info("setting key:"+(responseObj.get("userName").toString().trim().toLowerCase())); + if ((responseObj.get("userName")) != null && (responseObj.get("userName").toString()) != null) { + logger.info("setting key:" + (responseObj.get("userName").toString().trim().toLowerCase())); sessionObject.setSessionObject((responseObj.get("userName").toString().trim().toLowerCase()), key); } } catch (Exception e) { @@ -876,7 +951,7 @@ public void userForceLogout(ForceLogoutRequestModel request) throws Exception { throw new Exception("Force logout failed due to incorrect username"); } try { - if (!securePassword.validatePassword(request.getPassword(), users.get(0).getPassword())) { + if (!securePassword.validatePasswordExisting(request.getPassword(), users.get(0).getPassword())) { throw new Exception("Force logout failed due to incorrect password"); } } catch (Exception e) { @@ -971,7 +1046,7 @@ public List userAuthenticateByEncryption(String req) throws Exception { } User user = users.get(0); try { - if (!securePassword.validatePassword(m_user.getPassword(), user.getPassword())) { + if (!securePassword.validatePasswordExisting(m_user.getPassword(), user.getPassword())) { throw new IEMRException("User login failed due to incorrect username/password"); } } catch (Exception e) { @@ -1057,7 +1132,36 @@ public String validateQuestionAndAnswersForPasswordChange(JsonObject request) th } } - + + public String generateStrongPasswordForExistingUser(String password) + throws NoSuchAlgorithmException, InvalidKeySpecException { + int iterations = 1000; + char[] chars = password.toCharArray(); + byte[] salt = getSalt(); + + PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 512); + SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); + byte[] hash = skf.generateSecret(spec).getEncoded(); + return iterations + ":" + toHex(salt) + ":" + toHex(hash); + } + + private byte[] getSalt() throws NoSuchAlgorithmException { + SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); + byte[] salt = new byte[16]; + sr.nextBytes(salt); + return salt; + } + + private String toHex(byte[] array) throws NoSuchAlgorithmException { + BigInteger bi = new BigInteger(1, array); + String hex = bi.toString(16); + int paddingLength = array.length * 2 - hex.length(); + if (paddingLength > 0) { + return String.format(new StringBuilder().append("%0").append(paddingLength).append("d").toString(), + new Object[] { Integer.valueOf(0) }) + hex; + } + return hex; + } } diff --git a/src/main/java/com/iemr/common/utils/encryption/AESUtil.java b/src/main/java/com/iemr/common/utils/encryption/AESUtil.java index 161176e7..e9d7b895 100644 --- a/src/main/java/com/iemr/common/utils/encryption/AESUtil.java +++ b/src/main/java/com/iemr/common/utils/encryption/AESUtil.java @@ -163,4 +163,64 @@ private static byte[] generateRandom(int length) { random.nextBytes(randomBytes); return randomBytes; } + + public String decryptExistingPwd(String passPhrase, String cipherText) { + try { + String salt = cipherText.substring(0, saltLength); + int ivLength = IV_SIZE / 4; + String iv = cipherText.substring(saltLength, saltLength + ivLength); + String ct = cipherText.substring(saltLength + ivLength); + return decryptExistingPwd(salt, iv, passPhrase, ct); + } catch (Exception e) { + return null; + } + } + + public String decryptExistingPwd(String salt, String iv, String passPhrase, String cipherText) { + try { + SecretKey key = generateKeyForExistingUser(salt, passPhrase); + byte[] encrypted; + if (dataType.equals(DataType.HEX)) { + encrypted = fromHex(cipherText); + } else { + encrypted = fromBase64(cipherText); + } + byte[] decrypted = doFinal(Cipher.DECRYPT_MODE, key, iv, encrypted); + return new String(Objects.requireNonNull(decrypted), StandardCharsets.UTF_8); + } catch (Exception e) { + return null; + } + } + + private SecretKey generateKeyForExistingUser(String salt, String passPhrase) { + try { + SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), fromHex(salt), iterationCount, keySize); + return new SecretKeySpec(secretKeyFactory.generateSecret(keySpec).getEncoded(), KEY_ALGORITHM); + } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { + logger.info(e.getMessage()); + } + return null; + } + + public String decryptExistingPwdNew(String passPhrase, String password) { + + try { + String[] parts = password.split(":"); + int iterations = Integer.parseInt(parts[0]); + String salt = parts[1]; + String hash = parts[2]; + SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + PBEKeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), fromHex(salt), iterationCount, hash.length() * 4); + SecretKey key = secretKeyFactory.generateSecret(keySpec); + + byte[] decryptedHash = key.getEncoded(); + return toHex(decryptedHash); + } catch (Exception e) { + throw new RuntimeException("Error decrypting password : " + e.getLocalizedMessage()); + } + } + + + }