Last active
December 14, 2016 10:57
-
-
Save webmstk/8bb89523e0a285fa95a5e77d9278e3f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OneTimePasswordGenerator | |
def initialize(pass_code_length = 6) | |
@pin_modulo = 10 ** pass_code_length | |
end | |
def get_code(base64_secret, time = nil) | |
time = (Time.current.to_i / 30).floor unless time | |
secret = Base64.decode64 base64_secret | |
time = [time].pack('N').rjust 8, "\0" | |
hash = OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha1'), secret, time) | |
offset = hash[-1].ord & 0xF | |
truncated_hash = hash_to_int(hash, offset) & 0x7FFFFFFF | |
(truncated_hash % @pin_modulo).to_s.rjust 6, '0' | |
end | |
private | |
def hash_to_int(bytes, start) | |
bytes.slice(start, bytes.size).slice(0, 4).unpack('N').first | |
end | |
end | |
p OneTimePasswordGenerator.new.get_code 'base64EncodedSecret' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment