/
passwordHasher.go
81 lines (69 loc) · 2.31 KB
/
passwordHasher.go
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"github.com/kless/osutil/user/crypt/apr1_crypt"
"github.com/kless/osutil/user/crypt/md5_crypt"
"github.com/kless/osutil/user/crypt/sha256_crypt"
"github.com/kless/osutil/user/crypt/sha512_crypt"
)
// HashPassword is used to generate a password hash of the correct type
func HashPassword(password, hashType string) (string, error) {
var hash string
var err error
switch hashType {
case "sha512":
hash, err = GenerateSHA512FromString(password)
case "sha256":
hash, err = GenerateSHA256FromString(password)
case "apr1":
hash, err = GenerateAPR1FromString(password)
case "md5":
hash, err = GenerateMD5FromString(password)
default:
hash = "Password cannot be a blank value. Please try again."
}
return hash, err
}
// GenerateSHA512FromString creates a SHA-512 password hash from a password
// string which is compatible with Linux operating systems.
func GenerateSHA512FromString(password string) (string, error) {
crypter := sha512_crypt.New()
passwordByteStream := []byte(password)
passwordHash, err := crypter.Generate(passwordByteStream, []byte{})
if err != nil {
return "", err
}
return passwordHash, nil
}
// GenerateSHA256FromString creates a SHA-256 password hash from a password
// string which is compatible with Linux operating systems.
func GenerateSHA256FromString(password string) (string, error) {
crypter := sha256_crypt.New()
passwordByteStream := []byte(password)
passwordHash, err := crypter.Generate(passwordByteStream, []byte{})
if err != nil {
return "", err
}
return passwordHash, nil
}
// GenerateAPR1FromString creates a APR1 password hash from a password
// string which is compatible with Linux operating systems.
func GenerateAPR1FromString(password string) (string, error) {
crypter := apr1_crypt.New()
passwordByteStream := []byte(password)
passwordHash, err := crypter.Generate(passwordByteStream, []byte{})
if err != nil {
return "", err
}
return passwordHash, nil
}
// GenerateMD5FromString creates an MD5 password hash from a password
// string which is compatible with Linux operating systems.
func GenerateMD5FromString(password string) (string, error) {
crypter := md5_crypt.New()
passwordByteStream := []byte(password)
passwordHash, err := crypter.Generate(passwordByteStream, []byte{})
if err != nil {
return "", err
}
return passwordHash, nil
}