forked from binarylogic/authlogic
/
sha512.rb
52 lines (48 loc) · 1.87 KB
/
sha512.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
require "digest/sha2"
module Authlogic
# = Crypto Providers
#
# The acts_as_authentic method allows you to pass a :crypto_provider option. This allows you to use any type of encryption you like.
# Just create a class with a class level encrypt and matches? method. See example below.
#
# === Example
#
# class MyAwesomeEncryptionMethod
# def self.encrypt(*tokens)
# # the tokens passed wil be an array of objects, what type of object is irrelevant
# # just do what you need to do with them and return a single encrypted string.
# # for example, you will most likely join all of the objects into a single string and then encrypt that string
# end
#
# def self.matches?(crypted, *tokens)
# # return true if the crypted string matches the tokens.
# # depending on your algorithm you might decrypt the string then compare it to the token, or you might
# # encrypt the tokens and make sure it matches the crypted string, its up to you
# end
# end
module CryptoProviders
# = Sha512
#
# Uses the Sha512 hash algorithm to encrypt passwords.
class Sha512
class << self
attr_accessor :join_token
# The number of times to loop through the encryption. This is ten because that is what restful_authentication defaults to.
def stretches
@stretches ||= 20
end
attr_writer :stretches
# Turns your raw password into a Sha512 hash.
def encrypt(*tokens)
digest = tokens.flatten.join(join_token)
stretches.times { digest = Digest::SHA512.hexdigest(digest) }
digest
end
# Does the crypted password match the tokens? Uses the same tokens that were used to encrypt.
def matches?(crypted, *tokens)
encrypt(*tokens) == crypted
end
end
end
end
end