forked from Azure/go-pkcs12
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mac.go
57 lines (47 loc) · 1.26 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
package pkcs12
import (
"crypto/hmac"
"crypto/sha1"
"crypto/x509/pkix"
"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 (
hashNameByID = map[string]string{
"1.3.14.3.2.26": 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 UnsupportedFormat("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 PasswordIncorrect("Incorrect password, MAC mismatch")
}
return nil
}
// PasswordIncorrect Error indicates that the supplied password is incorrect.
// Usually, P12/PFX data is signed to be able to verify the password.
type PasswordIncorrect string
func (e PasswordIncorrect) Error() string { return string(e) }