improve hmac validation
parent
005219895e
commit
dfcb555de1
@ -1,29 +0,0 @@
|
||||
// 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 sha1
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
// Validate checks the hmac signature of the message.
|
||||
func Validate(message, key, signature []byte) bool {
|
||||
mac := hmac.New(sha1.New, key)
|
||||
mac.Write(message)
|
||||
sum := mac.Sum(nil)
|
||||
return hmac.Equal(signature, sum)
|
||||
}
|
||||
|
||||
// ValidateEncoded checks the hmac signature of the mssasge
|
||||
// using a hex encoded signature.
|
||||
func ValidateEncoded(message, key []byte, signature string) bool {
|
||||
decoded, err := hex.DecodeString(signature)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return Validate(message, key, decoded)
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
// 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 sha1
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
msg string
|
||||
key string
|
||||
sig string
|
||||
res bool
|
||||
}{
|
||||
{
|
||||
msg: `{"yo":true}`,
|
||||
key: "0123456789abcdef",
|
||||
sig: "126f2c800419c60137ce748d7672e77b65cf16d6",
|
||||
res: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
res := ValidateEncoded(
|
||||
[]byte(test.msg),
|
||||
[]byte(test.key),
|
||||
test.sig,
|
||||
)
|
||||
if res != test.res {
|
||||
t.Errorf("Want valid %v for message %q",
|
||||
test.res, test.msg)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue