This commit is contained in:
Malte Schulze Hobeling 2023-01-16 17:23:25 +01:00
parent 0fcc477613
commit 438d18e378

View File

@ -6,6 +6,7 @@ package com.bib.essensbestellungsverwaltung;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.ArrayList;
@ -52,7 +53,7 @@ public class AccountMgr {
String[] userH = {"name", "firstname", "addressid", "password", "email"};
String name = userData[0];
String firstname = userData[1];
String pw = hashAndSalt(userData[2]);
String pw = hashAndSalt(userData[2], getSalt());
String email = userData[3];
long id = Database.insert("address", addressH, addressData);
@ -102,8 +103,14 @@ public class AccountMgr {
* @return id or -1
*/
protected static long login(String email, String pw){
String[] pwH = {"email"};
String[] pwD = {email};
List<String> foundEmail = Database.select("user",pwH,pwD);
String[] userParts = foundEmail.get(0).split(":");
String[] pwParts = userParts[4].split("\\.");
String salt = pwParts[1];
String[] userH = {"email","password"};
String[] userD = {email,hashAndSalt(pw)};
String[] userD = {email,hashAndSalt(pw,salt)};
return Database.getSingleId("user",userH,userD);
}
@ -136,10 +143,10 @@ public class AccountMgr {
* @param pw the password to hash
* @return hashed and salted password
*/
protected static String hashAndSalt(String pw){
//todo: find a better way to salt
byte[] magicSalt = new byte[]{96, 13, 100, 85, -37, 52, -123, 86, -123, -92, 16, 15, -110, -42, -49, 0};
KeySpec spec = new PBEKeySpec(pw.toCharArray(), magicSalt,310001,256);
protected static String hashAndSalt(String pw, String salt){
Base64.Decoder dec = Base64.getDecoder();
byte[] bySalt = dec.decode(salt);
KeySpec spec = new PBEKeySpec(pw.toCharArray(), bySalt,310001,256);
String hashedPw;
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
@ -149,9 +156,18 @@ public class AccountMgr {
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
hashedPw += "." + salt;
return hashedPw;
}
private static String getSalt(){
SecureRandom sec = new SecureRandom();
byte[] salt = new byte[16];
sec.nextBytes(salt);
Base64.Encoder enc = Base64.getEncoder();
return enc.encodeToString(salt);
}
/**
* gives the invoice for one month and one child
* @param date YYYY-MM the month