Created
May 23, 2011 23:19
-
-
Save bithive/987839 to your computer and use it in GitHub Desktop.
Generate Google Authenticator codes in Ruby (requires base32 gem)
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
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'base32' | |
require 'openssl' | |
int = 30 | |
now = Time.now.to_i / int | |
key = Base32.decode File.read('secret.key').strip | |
sha = OpenSSL::Digest::Digest.new('sha1') | |
(-1..1).each do |x| | |
bytes = [ now + x ].pack('>q').reverse | |
hmac = OpenSSL::HMAC.digest(sha, key.to_s, bytes) | |
offset = hmac[-1] & 0x0F | |
hash = hmac[offset...offset + 4] | |
code = hash.reverse.unpack('L')[0] | |
code &= 0x7FFFFFFF | |
code %= 1000000 | |
puts code | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment