Skip to content

Instantly share code, notes, and snippets.

@bithive
Created May 23, 2011 23:19
Show Gist options
  • Save bithive/987839 to your computer and use it in GitHub Desktop.
Save bithive/987839 to your computer and use it in GitHub Desktop.
Generate Google Authenticator codes in Ruby (requires base32 gem)
#!/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