/
mac.go
62 lines (53 loc) · 1.35 KB
/
mac.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
package pkcs12
import (
"crypto/hmac"
"crypto/sha1"
"crypto/x509/pkix"
"encoding/asn1"
"hash"
)
type macData struct {
Mac digestInfo
MacSalt []byte
Iterations int `asn1:"optional,default:1"`
}
// from PKCS#7:
type digestInfo struct {
Algorithm pkix.AlgorithmIdentifier
Digest []byte
}
const (
sha1Algorithm = "SHA-1"
)
var (
oidSha1Algorithm = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 26}
hashNameByID = map[string]string{
oidSha1Algorithm.String(): sha1Algorithm,
}
hashByName = map[string]func() hash.Hash{
sha1Algorithm: sha1.New,
}
)
func verifyMac(macData *macData, message, password []byte) error {
name, ok := hashNameByID[macData.Mac.Algorithm.Algorithm.String()]
if !ok {
return NotImplementedError("unknown digest algorithm: " + macData.Mac.Algorithm.Algorithm.String())
}
k := deriveMacKeyByAlg[name](macData.MacSalt, password, macData.Iterations)
password = nil
mac := hmac.New(hashByName[name], k)
mac.Write(message)
expectedMAC := mac.Sum(nil)
if !hmac.Equal(macData.Mac.Digest, expectedMAC) {
return ErrIncorrectPassword
}
return nil
}
func generateMacSha1(message, salt, password []byte, iterations int) ([]byte, error) {
name := sha1Algorithm
k := deriveMacKeyByAlg[name](salt, password, iterations)
password = nil
mac := hmac.New(hashByName[name], k)
mac.Write(message)
return mac.Sum(nil), nil
}