Skip to content

Instantly share code, notes, and snippets.

@benaubin
Created June 2, 2020 13:52
Show Gist options
  • Save benaubin/863b2bfb7f12c535e94c60dacfd25d07 to your computer and use it in GitHub Desktop.
Save benaubin/863b2bfb7f12c535e94c60dacfd25d07 to your computer and use it in GitHub Desktop.
module SecureBearerToken
TOKEN_BYTES = 33
def self.generate_token
token = SecureRandom.random_bytes(TOKEN_BYTES)
hash = hash_decoded_token token
[Base64.urlsafe_encode64(token), hash]
end
def self.hash_encoded_token(token)
hash_decoded_token(Base64.urlsafe_decode64(token))
end
private
def self.hash_decoded_token(token)
digest = peppered_hash.update(token)
digest.digest[0..TOKEN_BYTES]
end
# by peppering our hashes, we resist a possible yet-difficult timing attack
def self.peppered_hash
(@peppered_hash ||= begin
digest = Digest::SHA512.new
pepper = Rails.application.key_generator.generate_key("This is the salt to generate the pepper for secure bearer tokens.", digest.block_length)
digest.update pepper
end).dup
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment