This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/src/main/java/envoy/data/LoginCredentials.java

73 lines
2.0 KiB
Java

package envoy.data;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
/**
* Project: <strong>envoy-common</strong><br>
* File: <strong>LoginCredentials.java</strong><br>
* Created: <strong>29.12.2019</strong><br>
*
* @author Kai S. K. Engelbart
* @since Envoy Common v0.2-alpha
*/
public class LoginCredentials implements Serializable {
private static final long serialVersionUID = -7395245059059523314L;
private final String name;
private final byte[] passwordHash;
/**
* Creates an in stance of {@link LoginCredentials}.
*
* @param name the name of the user
* @param password the password of the user (will be converted to a hash)
* @throws NoSuchAlgorithmException if the algorithm used is unknown
* @since Envoy Common v0.2-alpha
*/
public LoginCredentials(String name, char[] password) throws NoSuchAlgorithmException {
this.name = name;
passwordHash = getSha256(toByteArray(password));
}
/**
* @return the name of the user performing the login
* @since Envoy Common v0.2-alpha
*/
public String getName() { return name; }
/**
* @return the password hash of the user performing the login
* @since Envoy Common v0.2-alpha
*/
public byte[] getPasswordHash() { return passwordHash; }
private byte[] getSha256(byte[] input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(input);
}
private byte[] toByteArray(char[] chars) {
byte[] bytes = new byte[chars.length * 2];
for (int i = 0; i < chars.length; ++i) {
bytes[i * 2] = (byte) (chars[i] >> 8);
bytes[i * 2 + 1] = (byte) (chars[i]);
}
return bytes;
}
@Override
public String toString() {
try (Formatter form = new Formatter()) {
form.format("LoginCredentials[name=%s,passwordHash=", name);
for (byte element : passwordHash) {
form.format("%02x", element);
}
form.format("]");
String str = form.toString();
return str;
}
}
}