totp_util.dart 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import 'package:ente_auth/models/code.dart';
  2. import 'package:flutter/foundation.dart';
  3. import 'package:otp/otp.dart' as otp;
  4. String getOTP(Code code) {
  5. if (code.type == Type.hotp) {
  6. return _getHOTPCode(code);
  7. }
  8. return otp.OTP.generateTOTPCodeString(
  9. getSanitizedSecret(code.secret),
  10. DateTime.now().millisecondsSinceEpoch,
  11. length: code.digits,
  12. interval: code.period,
  13. algorithm: _getAlgorithm(code),
  14. isGoogle: true,
  15. );
  16. }
  17. String _getHOTPCode(Code code) {
  18. return otp.OTP.generateHOTPCodeString(
  19. getSanitizedSecret(code.secret),
  20. code.counter,
  21. length: code.digits,
  22. algorithm: _getAlgorithm(code),
  23. isGoogle: true,
  24. );
  25. }
  26. String getNextTotp(Code code) {
  27. return otp.OTP.generateTOTPCodeString(
  28. getSanitizedSecret(code.secret),
  29. DateTime.now().millisecondsSinceEpoch + code.period * 1000,
  30. length: code.digits,
  31. interval: code.period,
  32. algorithm: _getAlgorithm(code),
  33. isGoogle: true,
  34. );
  35. }
  36. otp.Algorithm _getAlgorithm(Code code) {
  37. switch (code.algorithm) {
  38. case Algorithm.sha256:
  39. return otp.Algorithm.SHA256;
  40. case Algorithm.sha512:
  41. return otp.Algorithm.SHA512;
  42. default:
  43. return otp.Algorithm.SHA1;
  44. }
  45. }
  46. String getSanitizedSecret(String secret) {
  47. return secret.toUpperCase().trim().replaceAll(' ', '');
  48. }
  49. String safeDecode(String value) {
  50. try {
  51. return Uri.decodeComponent(value);
  52. } catch (e) {
  53. // note: don't log the value, it might contain sensitive information
  54. debugPrint("Failed to decode $e");
  55. return value;
  56. }
  57. }