forked from publiclab/mapknitter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
password.rb
54 lines (43 loc) · 1.14 KB
/
password.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
53
54
require 'digest/sha2'
# This module contains functions for hashing and storing passwords
module Password
# Generates a new salt and rehashes the password
def Password.update(password)
salt = self.salt
hash = self.hash(password,salt)
self.store(hash, salt)
end
# Checks the password against the stored password
def Password.check(password, store)
hash = self.get_hash(store)
salt = self.get_salt(store)
if self.hash(password,salt) == hash
true
else
false
end
end
protected
# Generates a psuedo-random 64 character string
def Password.salt
salt = ""
64.times { salt << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
salt
end
# Generates a 128 character hash
def Password.hash(password,salt)
Digest::SHA512.hexdigest("#{password}:#{salt}")
end
# Mixes the hash and salt together for storage
def Password.store(hash, salt)
hash + salt
end
# Gets the hash from a stored password
def Password.get_hash(store)
store[0..127]
end
# Gets the salt from a stored password
def Password.get_salt(store)
store[128..192]
end
end