-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
84 lines (73 loc) · 1.91 KB
/
hash.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
82
83
84
package gocrypto
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"errors"
"fmt"
)
type GoHashCrypto struct {
privateKey *rsa.PrivateKey
publicKey *rsa.PublicKey
hashFunc crypto.Hash
}
// NewHashCrypto
func NewHashCrypto() (*GoHashCrypto, error) {
keyPair, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, fmt.Errorf("failed to generate RSA key pair: %v", err)
}
g := &GoHashCrypto{
privateKey: keyPair,
publicKey: &keyPair.PublicKey,
hashFunc: crypto.SHA256,
}
return g, nil
}
// SetHashFunction
func (g *GoHashCrypto) SetHashFunction(hashFunc string) error {
switch hashFunc {
case "MD5":
g.hashFunc = crypto.MD5
case "SHA256":
g.hashFunc = crypto.SHA256
case "SHA512":
g.hashFunc = crypto.SHA512
default:
return errors.New("invalid hash function")
}
return nil
}
// HashString
// it will return the hash of given string using the hash function used
func (g *GoHashCrypto) HashString(data string) (string, error) {
hasher := g.hashFunc.New()
_, err := hasher.Write([]byte(data))
if err != nil {
return "", fmt.Errorf("error writing data to hash function: %v", err)
}
sum := hasher.Sum(nil)
hashedData := base64.StdEncoding.EncodeToString(sum)
return hashedData, nil
}
// CheckSignature
func (g *GoHashCrypto) CheckSignature(hashedPassword string) bool {
if g.publicKey == nil {
return false
}
decodedHash, _ := base64.StdEncoding.DecodeString(hashedPassword)
signature, _ := rsa.SignPKCS1v15(rand.Reader, g.privateKey, g.hashFunc, decodedHash)
// Verify signature using public key
err := rsa.VerifyPKCS1v15(g.publicKey, g.hashFunc, decodedHash, signature)
return err == nil
}
// CheckPasswordHash
// checks if a given password matches the hashed password
func (g *GoHashCrypto) CheckPasswordHash(password, hashedPassword string) bool {
hash, err := g.HashString(password)
if err != nil {
return false
}
return hash == hashedPassword
}