Skip to content

Commit

Permalink
Added getHashPassword to PasswordHasher
Browse files Browse the repository at this point in the history
  • Loading branch information
robinsp committed Mar 3, 2026
1 parent 05cb45b commit 0a4721e
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 3 deletions.
6 changes: 6 additions & 0 deletions helpmehelpapplication/helpmehelpapplication.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="CheckStyle-IDEA-Module" serialisationVersion="2">
<option name="activeLocationsIds" />
</component>
</module>
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package ntnu.sytemutvikling.team6.models;

import javax.crypto.SecretKeyFactory;
import javax.crypto.interfaces.PBEKey;
import javax.crypto.spec.PBEKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
* A password hasher
*
* <p>
* Description
* <p/>
*
* @author Robin Strand Prestmo
*/
public final class PasswordHasher {
private static final SecureRandom RNG = new SecureRandom();

/**
* Get the hash of the password
*
* @param password a string password
* @return a hash secured password
*/
public String getHashPassword(String password) {
String hasPass = "";

try {
// 1. Create salt
byte[] salt = new byte[16];
RNG.nextBytes(salt);

// 2. Create PBKDF2 Hash value
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 100000, 32*8);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
byte[] hash = factory.generateSecret(spec).getEncoded();

// 3. Combine salt and password bytes
byte[] hashBytes = new byte[48];
System.arraycopy(salt, 0, hashBytes, 0, 16);
System.arraycopy(hash, 0, hashBytes, 16, 32);

//4. Turn the combined salt+hash into a string.
hasPass = Base64.getEncoder().encodeToString(hashBytes);
} catch (Exception e) {
throw new RuntimeException("Error while hasing password.", e);
}
return hasPass;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import java.util.UUID;

// Passord må hashes!!!
// Unntakshåndtering mangler
// Enhetstesting mangler
// TODO: Passord må hashes!!!
// TODO: Unntakshåndtering mangler
// TODO: Enhetstesting mangler

/**
* Represents a user.
Expand Down

0 comments on commit 0a4721e

Please sign in to comment.