Created
June 2, 2020 13:52
-
-
Save benaubin/863b2bfb7f12c535e94c60dacfd25d07 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
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