I´m trying to implement a login screen where all your inputs get encrypted by SHA 512 and some minor tweaks to the function later (reversing the string, extending the length). For my username the encryption works well but my passwords on the other hand gives me the same result, no matter what i type in.
public static String password_encrypt(String input) {
try {
String password_ = input;
int iterations = 250000;
String salt = "salt";
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
char[] passwordChars = password_.toCharArray();
KeySpec spec = new PBEKeySpec(passwordChars, salt.getBytes(), iterations, 256);
SecretKey key = factory.generateSecret(spec);
byte[] passwordHash = key.getEncoded();
SecretKey secret = new SecretKeySpec(key.getEncoded(), "AES");
input = secret.toString();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return input;
}
And then i check in an array if there is a place where i can put the information and i if there is one its getting stored there.
for (int i = 0; i < username.length; i++) {
System.out.println("username " + username[i]);
if (name.equals(username[i])) {
System.out.println("Dieser Username ist bereits vergeben!");
break;
}
if ("empty".equals(username[i]) || null == username[i]) {
username[i] = name;
stelle = i;
System.out.println("Username wurde vergeben");
break;
}
else if (name.equals(username[i])) {
System.out.println("1234");
}
}
for (int j = 0; j < password.length; j++) {
System.out.println("Passwort " + password[j]);
if ("empty".equals(password[j]) || null == password[j]) {
System.out.println("Passwort wurde vergeben");
password[j] = input_;
stelle_pw = j;
break;
}
else if (input.equals(password[j])) {
System.out.println("123");
}
}
The arrays username[] and password[] were filled with "empty" or null by my constructor.
My major problem is: no matter what the input for the password is, i am getting the same key: javax.crypto.spec.SecretKeySpec@fffea4cc
This gives me a big security leak if i just compare the strings to decide if its the right one...
Little Disclamer: Some functions or variables are made with _ because i am dyslexic. Please dont butcher me for not using the name convention. T
There are several things wrong with the provided code, first of all it uses a static weak salt. While there are better algorithms to protect a password than PBKDF2 (➽ Argon2, BCrypt, SCrypt), it can be used if implemented correctly. There I would like to recommend the well known library Defuse, which makes password hashing and verification a breeze, it can be included as single class file.
BTW a hashed password cannot be reversed, hashing is not the same as encryption.