Generating and storing a unique salt in Oracle database using Java This is my account table:

CREATE TABLE mwUser (
  username varchar2(20) primary key not null, 
  salt varchar2(64) unique not null,
  hashedpw varchar2(64) not null, 
  email varchar2(320) unique not null 
);


When I register a new user with my java webservice I automatically generate a random salt and store in the database base (see code below):

Connection c = dataSource.getConnection(); 
Statement stmt = c.createStatement();
boolean isFound=true;
String randomSalt="";
while(isFound){
   isFound=false;
   String randomSalt=createRandomString(); //creates salt/random string
   ResultSet rs = stmt.executeQuery("SELECT * FROM mvUser where salt="+randomString);
   //check if salt is unique
   while (rs.next()) {
     isFound=true;
   }
}

Statement insertStmt = c.createStatement();
String hashedPW=hash(randomSalt+pw); //generates hashed pw
ResultSet rs = stmt.executeQuery("INSERT INTO mvUser VALUES(.....));

stmt.close();
c.close();


But as you can see, from my point of view my code is not clean/performant/readable because I have two statements (for checking if salt is unique and and second statement is for inserting).

How can I automatically generate an unique string(salt) and hash it at the same time. I am trying to make my code more performant and read able.
Please use best practices in general when dealing with password hashing.


If you have to verify the database for your generated salt to be unique, you're using a bad salt generator. Make sure to focus on using a good generator instead.
Your hash function also seems weak. Consider using key stretching.




This should not be required:


while(isFound){
   isFound=false;
   String randomSalt=createRandomString(); //creates salt/random string
   ResultSet rs = stmt.executeQuery("SELECT * FROM mvUser where salt="+randomString);
   //check if salt is unique
   while (rs.next()) {
     isFound=true;
   }
}



And for hash, I would expect something like below, where hash is an established hash library (PBKDF2, bcrypt, scrypt, ..).

var hashedPW = hash(iterations, randomSalt, pw);