forked from drone/go-scm
-
Notifications
You must be signed in to change notification settings - Fork 83
/
hmac.go
48 lines (43 loc) · 1.18 KB
/
hmac.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
// Copyright 2017 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package hmac
import (
"crypto/hmac"
"crypto/sha1" // #nosec
"crypto/sha256"
"encoding/hex"
"hash"
"strings"
)
// Validate checks the hmac signature of the mssasge
// using a hex encoded signature.
func Validate(h func() hash.Hash, message, key []byte, signature string) bool {
decoded, err := hex.DecodeString(signature)
if err != nil {
return false
}
return validate(h, message, key, decoded)
}
// ValidatePrefix checks the hmac signature of the message
// using the message prefix to determine the signing algorithm.
func ValidatePrefix(message, key []byte, signature string) bool {
parts := strings.Split(signature, "=")
if len(parts) != 2 {
return false
}
switch parts[0] {
case "sha1":
return Validate(sha1.New, message, key, parts[1])
case "sha256":
return Validate(sha256.New, message, key, parts[1])
default:
return false
}
}
func validate(h func() hash.Hash, message, key, signature []byte) bool {
mac := hmac.New(h, key)
mac.Write(message) // #nosec
sum := mac.Sum(nil)
return hmac.Equal(signature, sum)
}