Skip to content

Add a salt to SHA256 hash #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions Travelbook/src/main/java/travelbook/controller/AllQuery.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import main.java.travelbook.model.StepEntity;
import main.java.travelbook.model.TravelEntity;
import main.java.travelbook.model.UserEntity;
import main.java.travelbook.util.HashUtil;

public class AllQuery {
private static AllQuery instance=null;
Expand All @@ -39,7 +40,7 @@ public static AllQuery getInstance() {
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(myUrl,"root","Sara.d-19");
}
private String userAttributeQuery="Select idUser,NameUser,Surname,Birthdate,DescriptionProfile,Email,FollowerNumber,FollowingNumber,TripNumber,ProfileImage,Gender,Nazionalita";
private String userAttributeQuery="Select idUser,NameUser,Surname,Birthdate,DescriptionProfile,Email,FollowerNumber,FollowingNumber,TripNumber,ProfileImage,Gender,Nazionalita,password";
public ResultSet searchTrip(Statement stmt,SearchEntity entity) throws SQLException
{
if(entity.getMaxCost()==null) {
Expand Down Expand Up @@ -71,15 +72,15 @@ public ResultSet requestLogin(Statement stmt,String username,String password) th


if(rs.next()) {
rs= stmt.executeQuery(userAttributeQuery+" FROM User where Username='"+username+"' and password='"+password+"'");
if(!rs.next()) throw new ExceptionLogin("Errore Password");
String passwordHash = rs.getString("password");
if (!HashUtil.validatePassword(password, passwordHash)) throw new ExceptionLogin("Errore Password");
}
else {
rs = stmt.executeQuery(userAttributeQuery+" FROM User where email='"+username+"'");
if(rs.next()) {
rs= stmt.executeQuery(userAttributeQuery+" FROM User where email='"+username+"' and password='"+password+"'");
if(!rs.next()) throw new ExceptionLogin("Errore Password");
}
String passwordHash = rs.getString("password");
if (!HashUtil.validatePassword(password, passwordHash)) throw new ExceptionLogin("Errore Password");
}
else throw new ExceptionLogin("Errore Username o password");
}

Expand Down Expand Up @@ -148,7 +149,7 @@ public void requestRegistrationUser(Connection conn,UserEntity user) throws SQLE
try {
preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, user.getUsername());
preparedStmt.setString (2, user.getPassword());
preparedStmt.setString (2, HashUtil.getPasswordHash(user.getPassword()));
preparedStmt.setString (3, user.getName());
preparedStmt.setString (4, user.getSurname());
preparedStmt.setDate (5,user.getBirthDate());// il data va sistemato
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@


import java.sql.SQLException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.List;
import java.util.Random;

import javax.mail.MessagingException;

import main.java.travelbook.model.Entity;
import main.java.travelbook.model.UserEntity;
import main.java.travelbook.model.bean.RegistrationBean;
Expand All @@ -26,30 +26,13 @@ public static ControllerLogin getInstance() {
instance = new ControllerLogin();
return instance;
}
private String passwordHash(String pswd)throws Exception {
MessageDigest hasher=MessageDigest.getInstance("SHA-1");
hasher.update(pswd.getBytes("UTF-8"));
return toHex(hasher.digest());
}
private static String toHex(byte[] data) {
StringBuilder sb = new StringBuilder();
for (byte b : data) {
String digit = Integer.toString(b & 0xFF, 16);

if (digit.length() == 1) {
sb.append("0");
}
sb.append(digit);
}
return sb.toString();
}
public UserBean signIn(String username,String password) throws SQLException{
UserBean user=null;
PersistanceDAO userDao=DaoFactory.getInstance().create(DaoType.USER);
UserEntity userE=new UserEntity();
userE.setUsername(username);
try {
userE.setPassword(this.passwordHash(password));
userE.setPassword(password);
}catch(Exception e) {
throw new SQLException(e.getMessage());
}
Expand Down Expand Up @@ -90,7 +73,7 @@ public void signUp(RegistrationBean user) throws SQLException{
PersistanceDAO userDao= DaoFactory.getInstance().create(DaoType.USER);
UserEntity newUser= new UserEntity(user);
try {
newUser.setPassword(this.passwordHash(user.getPassword()));
newUser.setPassword(user.getPassword());
}catch(Exception e) {
e.getStackTrace();
}
Expand Down
95 changes: 95 additions & 0 deletions Travelbook/src/main/java/travelbook/util/HashUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package main.java.travelbook.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
* Utility program for SHA256 hash.
* @author luchua-bc
* @version 1.0
*/
public class HashUtil {
private static final String SSHA_PREFIX = "{SSHA}";
private static final int SSHA_256_LENGTH = 32; // SHA-256 is 32 bytes long
private static final int SALT_LENGTH = 16; // Use a 16 byte salt

/**
* Returns the password hash with a random salt added.
* @param password The clear-text password to be hashed
*/
public static String getPasswordHash(String password) {
try {
byte[] salt = getSalt();
String cipher = getSaltedPasswordHash(password, salt);

return cipher;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}

/**
* Checks whether a password matches a previously generated password hash.
* @param password The clear-text password to be checked
* @param passwordHash The password hash that was previously generated from a password
*/
public static boolean validatePassword(String password, String passwordHash) {
boolean isValid = false;
try {
String cipher = passwordHash.substring(SSHA_PREFIX.length());

byte[] cipherBytes = Base64.getDecoder().decode(cipher.getBytes());
byte[] salt = new byte[SALT_LENGTH];
System.arraycopy(cipherBytes, SSHA_256_LENGTH, salt, 0, SALT_LENGTH);

String result = getSaltedPasswordHash(password, salt);
// Compare the newly hashed password taking the same salt with the input hash.
isValid = result.equals(passwordHash);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return isValid;
}

/**
* Returns a randomly generated salt with the specified length.
* @throws NoSuchAlgorithmException
*/
private static byte[] getSalt() throws NoSuchAlgorithmException {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_LENGTH];
random.nextBytes(salt);
return salt;
}

/**
* Generates a salted password with the given clear-text password and the salt.
* @param password The clear-text password to be hashed
* @param salt The salt to be added to the password hash
* @throws NoSuchAlgorithmException
*/
private static String getSaltedPasswordHash(String password, byte[] salt) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
// Add the salt to the message digest
md.update(salt);

byte[] passBytes = password.getBytes();
byte[] allBytes = new byte[passBytes.length + SALT_LENGTH];
System.arraycopy(passBytes, 0, allBytes, 0, passBytes.length);
System.arraycopy(salt, 0, allBytes, passBytes.length, SALT_LENGTH);

// Hash both the password and the salt
byte[] messageDigest = md.digest(allBytes);

// Combine the hash and the hashed password
byte[] cipherBytes = new byte[SSHA_256_LENGTH + SALT_LENGTH];
System.arraycopy(messageDigest, 0, cipherBytes, 0, SSHA_256_LENGTH);
System.arraycopy(salt, 0, cipherBytes, SSHA_256_LENGTH, SALT_LENGTH);

String result = SSHA_PREFIX + Base64.getEncoder().encodeToString(cipherBytes);
return result;
}
}