Spigot2FA/src/main/java/eu/oskar3123/spigot2fa/tfa/TFA.java

53 lines
1.8 KiB
Java

package eu.oskar3123.spigot2fa.tfa;
import org.apache.commons.codec.binary.Base32;
import org.apache.commons.codec.binary.Hex;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.SecureRandom;
public class TFA
{
public static String getRandomSecretKey()
{
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);
Base32 base32 = new Base32();
String secretKey = base32.encodeToString(bytes);
// make the secret key more human-readable by lower-casing and
// inserting spaces between each group of 4 characters
return secretKey.toUpperCase();
}
public static String getTOTPCode(String secretKey)
{
String normalizedBase32Key = secretKey.replace(" ", "").toUpperCase();
Base32 base32 = new Base32();
byte[] bytes = base32.decode(normalizedBase32Key);
String hexKey = Hex.encodeHexString(bytes);
long time = (System.currentTimeMillis() / 1000) / 30;
String hexTime = Long.toHexString(time);
return TOTP.generateTOTP(hexKey, hexTime, "6");
}
public static String getGoogleAuthenticatorBarCode(String secretKey, String issuer, String account)
{
String normalizedBase32Key = secretKey.replace(" ", "").toUpperCase();
try
{
return "otpauth://totp/"
+ URLEncoder.encode(issuer + ":" + account, "UTF-8").replace("+", "%20")
+ "?secret=" + URLEncoder.encode(normalizedBase32Key, "UTF-8").replace("+", "%20")
+ "&issuer=" + URLEncoder.encode(issuer, "UTF-8").replace("+", "%20");
}
catch (UnsupportedEncodingException e)
{
throw new IllegalStateException(e);
}
}
}