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

88 lines
2.5 KiB
Java

package envoy.data;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
/**
* Contains a {@link User}'s login information.<br>
* <br>
* 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 final String identifier;
private final byte[] passwordHash;
private final boolean registration;
private static final long serialVersionUID = -7395245059059523314L;
/**
* Creates an instance of {@link LoginCredentials} for a new {@link User}.
*
* @param identifier the identifier of the user
* @param password the password of the user (will be converted to a hash)
* @param registration signifies that these credentials are used for user
* registration instead of user login
* @since Envoy Common v0.2-alpha
*/
public LoginCredentials(String identifier, char[] password, boolean registration) {
this.identifier = identifier;
passwordHash = getSha256(toByteArray(password));
this.registration = registration;
}
private byte[] getSha256(byte[] input) {
try {
return MessageDigest.getInstance("SHA-256").digest(input);
} catch (NoSuchAlgorithmException e) {
// This will never happen
throw new RuntimeException(e);
}
}
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[identifier=%s,passwordHash=", identifier);
for (int i = 0; i < 3; i++)
form.format("%02x", passwordHash[i]);
return form.format(",registration=%b]", registration).toString();
}
}
/**
* @return the identifier of the user performing the login
* @since Envoy Common v0.2-alpha
*/
public String getIdentifier() { return identifier; }
/**
* @return the password hash of the user performing the login
* @since Envoy Common v0.2-alpha
*/
public byte[] getPasswordHash() { return passwordHash; }
/**
* @return {@code true} if these credentials are used for user registration
* instead of user login
* @since Envoy Common v0.2-alpha
*/
public boolean isRegistration() { return registration; }
}