TOTPUtil.java 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. * Project: MFA Google Auth Plugin
  3. *
  4. * Class: TOTPUtil
  5. *
  6. * Utility class for handling Time-based One-Time Password (TOTP) operations
  7. * using Google Authenticator library. Provides methods to generate secrets,
  8. * create otpauth URLs for QR codes, and verify TOTP codes.
  9. *
  10. * Author: Allan Barcelos
  11. * Date: 2025-07-17
  12. */
  13. package io.jenkins.plugins;
  14. import com.warrenstrange.googleauth.GoogleAuthenticator;
  15. import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
  16. import hudson.util.Secret;
  17. public class TOTPUtil {
  18. public static GoogleAuthenticatorKey generateSecret() {
  19. GoogleAuthenticator gAuth = new GoogleAuthenticator();
  20. return gAuth.createCredentials();
  21. }
  22. public static String getQRBarcodeURL(String user, String host, String secret) {
  23. String issuer = host;
  24. return String.format("otpauth://totp/%s@%s?secret=%s&issuer=%s", user, host, secret, issuer);
  25. }
  26. public static boolean verifyCode(Secret secret, String code) {
  27. try {
  28. return verifyCode(secret.getPlainText(), code);
  29. } catch (Exception e) {
  30. return false;
  31. }
  32. }
  33. public static boolean verifyCode(String secret, String code) {
  34. try {
  35. int codeInt = Integer.parseInt(code);
  36. GoogleAuthenticator gAuth = new GoogleAuthenticator();
  37. return gAuth.authorize(secret, codeInt);
  38. } catch (NumberFormatException e) {
  39. return false;
  40. }
  41. }
  42. }