1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class Test {
public static void main(String[] args) throws NoSuchAlgorithmException {
byte[] salt = getRandomSalt();
System.out.println(Base64.getEncoder().encodeToString(salt));
byte[] password = "MotDePassEnClair".getBytes();
System.out.println(hashPass(password, salt));
System.out.println(hashPass("MotDePassEnClair", salt));
}
private static byte[] getRandomSalt() throws NoSuchAlgorithmException {
// Uses a secure Random not a simple Random
// Salt generation 64 bits long
byte[] bSalt = new byte[8];
SecureRandom.getInstance("SHA1PRNG").nextBytes(bSalt);
return bSalt;
}
private static String hashPass(byte[] password, byte[] salt) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return Base64.getEncoder().encodeToString(md.digest(combine(salt, password)));
}
private static String hashPass(String password, byte[] salt) {
return hashPass(password.getBytes(),salt);
}
public static byte[] combine(byte[] a, byte[] b) {
byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
} |
Partager