【发布时间】:2019-10-01 23:47:11
【问题描述】:
我有一个 PasswordEncryptionService,我在其中散列我的密码并将它们与用于散列它们的盐一起保存在我的 MySQL 数据库中。我将我的密码和我的 Salt 都保存为字节数组,我听说我可以将它们保存为 SQL 数据库中的 varbinary 类型。
这是我的代码:
//this method is used to retrieve the salt when a user is logging in
public static byte[] getSaltMethod(String username, String password) throws SQLException, LoginSampleException {
try {
Connection con = Connector.connection();
String SQL = "SELECT * from Users.Salt WHERE email = ?, password = ?";
PreparedStatement statement = con.prepareStatement(SQL);
statement.setString(1, username);
statement.setString(2, password);
ResultSet set = statement.executeQuery();
while (set.next()) {
// vi skal ikke have en blolb her alligevel
byte[] salt = set.getBytes("salt");
//release the blob and free up memory. (since JDBC 4.0)
/* jeg er i tivil om denne skal være her*/
return salt;
}
} catch (SQLException ex) {
Conf.MYLOGGER.log(Level.SEVERE, null, ex);
throw new LoginSampleException(ex.getSQLState());
}
return null;
}
//this method is used to save the user along with the salt when a user is signing up
public static void createUser(User user) throws LoginSampleException, NoSuchAlgorithmException
{
try {
PasswordEncryptionService PE = new PasswordEncryptionService();
byte[] salt = PE.generateSalt();
Connection con = Connector.connection();
String SQL = "INSERT INTO Users (email, password, phone, post, adress, role, salt) VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, user.getEmail());
ps.setString(2, user.getPassword());
ps.setString(3, user.getPhonenumber());
ps.setString(4, user.getPostalCode());
ps.setString(5, user.getAddress());
ps.setString(6, user.getRole());
ps.setBytes(7, salt);
ps.executeUpdate();
ResultSet ids = ps.getGeneratedKeys();
ids.next();
int id = ids.getInt(1);
user.setId(id);
} catch (SQLException ex) {
throw new LoginSampleException(ex.getMessage());
}
}
现在我有一个单独的方法来检索盐和登录人,我应该将盐保存在不同的表中,还是可以保存在用户对象中?我应该将其保存为 varbinary 还是仅保存为常规 varchar?
【问题讨论】: