test_otp.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from pwman_tstlib import *
  2. initTest(__file__)
  3. from base64 import b32decode
  4. from libpwman.otp import *
  5. class Test_OTP(TestCase):
  6. def test_totp(self):
  7. tBase = 1566319890
  8. results = {
  9. "SHA1" : {
  10. 1 : ("5", "2", "2"),
  11. 2 : ("75", "82", "92"),
  12. 3 : ("575", "982", "792"),
  13. 4 : ("7575", "5982", "3792"),
  14. 5 : ("67575", "95982", "93792"),
  15. 6 : ("667575", "995982", "893792"),
  16. 7 : ("2667575", "1995982", "1893792"),
  17. 8 : ("02667575", "81995982", "71893792"),
  18. },
  19. "SHA256" : {
  20. 1 : ("5", "5", "3"),
  21. 2 : ("55", "35", "23"),
  22. 3 : ("655", "735", "223"),
  23. 4 : ("8655", "4735", "9223"),
  24. 5 : ("08655", "34735", "89223"),
  25. 6 : ("108655", "834735", "589223"),
  26. 7 : ("5108655", "4834735", "0589223"),
  27. 8 : ("25108655", "64834735", "00589223"),
  28. },
  29. "SHA512" : {
  30. 1 : ("6", "7", "6"),
  31. 2 : ("16", "07", "36"),
  32. 3 : ("016", "907", "736"),
  33. 4 : ("0016", "8907", "4736"),
  34. 5 : ("70016", "38907", "54736"),
  35. 6 : ("670016", "038907", "254736"),
  36. 7 : ("0670016", "4038907", "6254736"),
  37. 8 : ("00670016", "94038907", "66254736"),
  38. },
  39. }
  40. for hmacHash in ("SHA1", "SHA256", "SHA512"):
  41. for nrDigits in range(1, 8 + 1):
  42. for t in range(tBase - 1, tBase + 30 + 1):
  43. otp = totp(key="ORSXG5A=",
  44. nrDigits=nrDigits,
  45. hmacHash=hmacHash,
  46. t=float(t))
  47. if t < tBase:
  48. self.assertEqual(otp, results[hmacHash][nrDigits][0])
  49. elif t < tBase + 30:
  50. self.assertEqual(otp, results[hmacHash][nrDigits][1])
  51. else:
  52. self.assertEqual(otp, results[hmacHash][nrDigits][2])
  53. self.assertEqual(otp,
  54. totp(key="ORSXG5A=".lower(),
  55. nrDigits=nrDigits,
  56. hmacHash=hmacHash,
  57. t=float(t)))
  58. self.assertEqual(otp,
  59. totp(key=b32decode("ORSXG5A=".encode("UTF-8")),
  60. nrDigits=nrDigits,
  61. hmacHash=hmacHash,
  62. t=float(t)))
  63. def test_totp_errors(self):
  64. self.assertRaises(OtpError, lambda: totp(key="ORSXG5A=", nrDigits=0))
  65. self.assertRaises(OtpError, lambda: totp(key="ORSXG5A=", nrDigits=9))
  66. self.assertRaises(OtpError, lambda: totp(key="ORSXG5A=", hmacHash="foobar"))
  67. self.assertRaises(OtpError, lambda: totp(key="ORSXG5A"))
  68. def test_hotp_errors(self):
  69. self.assertRaises(OtpError, lambda: hotp(key="ORSXG5A=", counter=-1))
  70. self.assertRaises(OtpError, lambda: hotp(key="ORSXG5A=", counter=2**64))