This repository was archived by the owner on Oct 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalgorithm_hmac.go
More file actions
54 lines (43 loc) · 1.38 KB
/
Copy pathalgorithm_hmac.go
File metadata and controls
54 lines (43 loc) · 1.38 KB
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
package httpsignatures
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"hash"
"errors"
)
const (
hmac1SignatureSize = 20
hmac256SignatureSize = 32
)
func Hmac1Sign(privateKey *[]byte, message []byte) (*[]byte, error) {
return Sign(privateKey, message, sha1.New, hmac1SignatureSize)
}
func Hmac256Sign(privateKey *[]byte, message []byte) (*[]byte, error) {
return Sign(privateKey, message, sha256.New, hmac256SignatureSize)
}
func Hmac1Verify(privateKey *[]byte, message []byte, sig *[]byte) (bool, error) {
return Verify(privateKey, message, sha1.New, sig, hmac1SignatureSize)
}
func Hmac256Verify(privateKey *[]byte, message []byte, sig *[]byte) (bool, error) {
return Verify(privateKey, message, sha256.New, sig, hmac256SignatureSize)
}
func Sign(privateKey *[]byte, message []byte, hashFunc func() hash.Hash, signatureSize int) (*[]byte, error) {
hash := hmac.New(hashFunc, *privateKey)
hash.Write(message)
signature := make([]byte, signatureSize)
copy(signature[:], hash.Sum(nil))
return &signature, nil
}
func Verify(privateKey *[]byte, message []byte, hashFunc func() hash.Hash, sig *[]byte, signatureSize int) (bool, error) {
calcSign, err := Sign(privateKey, message, hashFunc, signatureSize)
if err != nil {
return false, err
}
if bytes.Equal(*calcSign, *sig) {
return true, nil
} else {
return false, errors.New(ErrorSignaturesDoNotMatch)
}
}