webmarker-server/src/main/java/net/mindoverflow/webmarker/utils/security/EncryptionUtils.java

66 lines
1.9 KiB
Java

package net.mindoverflow.webmarker.utils.security;
import at.favre.lib.crypto.bcrypt.BCrypt;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class EncryptionUtils {
public static String hmacSha256(String key, String value)
{
byte[] keyBytes = key.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256");
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(value.getBytes());
byte[] hexBytes = new Hex().encode(rawHmac);
return new String(hexBytes, "UTF-8");
} catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static String bcrypt(String value)
{
return BCrypt.withDefaults().hashToString(12, value.toCharArray()); // todo: custom salt
}
public static boolean bcryptMatches(String storedValue, String unencrypted)
{
BCrypt.Result result = BCrypt.verifyer().verify(unencrypted.toCharArray(), storedValue);
return result.verified;
}
public static String handleEncoding(String encoding, String encodedPassword)
{
String password;
switch (encoding.toLowerCase())
{
case "plaintext":
password = encodedPassword;
break;
case "base64":
password = new String(Base64.getDecoder().decode(encodedPassword));
break;
default:
password = "";
break;
}
return password;
}
}