Module: TOTP
- Defined in:
- lib/totp.rb
Class Method Summary collapse
-
.passwords(secret, time = Time.now) ⇒ Object
Generate passwords based on the secret and time.
-
.secret ⇒ Object
Generate a random secret.
- .totp(hmac, time) ⇒ Object
-
.valid?(secret, pass, time = Time.now) ⇒ Boolean
Return whether or not the key is valid for the given secret.
Class Method Details
.passwords(secret, time = Time.now) ⇒ Object
Generate passwords based on the secret and time
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/totp.rb', line 34 def self.passwords(secret, time = Time.now) interval = time.to_i / 30 hmac = OpenSSL::HMAC.new( Base32.decode(secret), OpenSSL::Digest::SHA1.new, ) # Cover three 30 second intervals return [ totp(hmac, interval.pred), totp(hmac, interval), totp(hmac, interval.succ), ] end |
.secret ⇒ Object
Generate a random secret
7 8 9 |
# File 'lib/totp.rb', line 7 def self.secret return Base32.encode((0...10).map { rand(255).chr }.join) end |
.totp(hmac, time) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/totp.rb', line 16 def self.totp(hmac, time) bytes = [time].pack('>q').reverse hmac.reset hmac.update(bytes) code = hmac.digest offs = code[-1].ord & 0x0F hash = code[offs...offs + 4] pass = hash.reverse.unpack('L')[0] pass &= 0x7FFFFFFF pass %= 1000000 return pass end |
.valid?(secret, pass, time = Time.now) ⇒ Boolean
Return whether or not the key is valid for the given secret
12 13 14 |
# File 'lib/totp.rb', line 12 def self.valid?(secret, pass, time = Time.now) return self.passwords(secret, time).include?(pass) end |