59 lines
1.7 KiB
Go
59 lines
1.7 KiB
Go
package macx
|
|
|
|
import "testing"
|
|
|
|
type hmacCase struct {
|
|
name string
|
|
sum func([]byte, []byte) []byte
|
|
sumStr func([]byte, []byte) string
|
|
verify func([]byte, []byte, []byte) bool
|
|
verifyStr func([]byte, []byte, string) bool
|
|
}
|
|
|
|
func TestHMACVerifyCases(t *testing.T) {
|
|
msg := []byte("macx-verify-message")
|
|
key := []byte("macx-verify-key")
|
|
|
|
cases := []hmacCase{
|
|
{"md4", HmacMd4, HmacMd4Str, VerifyHmacMd4, VerifyHmacMd4Str},
|
|
{"md5", HmacMd5, HmacMd5Str, VerifyHmacMd5, VerifyHmacMd5Str},
|
|
{"sha1", HmacSHA1, HmacSHA1Str, VerifyHmacSHA1, VerifyHmacSHA1Str},
|
|
{"sha224", HmacSHA224, HmacSHA224Str, VerifyHmacSHA224, VerifyHmacSHA224Str},
|
|
{"sha256", HmacSHA256, HmacSHA256Str, VerifyHmacSHA256, VerifyHmacSHA256Str},
|
|
{"sha384", HmacSHA384, HmacSHA384Str, VerifyHmacSHA384, VerifyHmacSHA384Str},
|
|
{"sha512", HmacSHA512, HmacSHA512Str, VerifyHmacSHA512, VerifyHmacSHA512Str},
|
|
{"ripemd160", HmacRipeMd160, HmacRipeMd160Str, VerifyHmacRipeMd160, VerifyHmacRipeMd160Str},
|
|
}
|
|
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
sum := tc.sum(msg, key)
|
|
if !tc.verify(msg, key, sum) {
|
|
t.Fatalf("verify bytes should pass")
|
|
}
|
|
|
|
hexSum := tc.sumStr(msg, key)
|
|
if !tc.verifyStr(msg, key, hexSum) {
|
|
t.Fatalf("verify hex should pass")
|
|
}
|
|
if !tc.verifyStr(msg, key, " \t"+hexSum+"\n") {
|
|
t.Fatalf("verify hex with spaces should pass")
|
|
}
|
|
|
|
bad := make([]byte, len(sum))
|
|
copy(bad, sum)
|
|
bad[0] ^= 0xff
|
|
if tc.verify(msg, key, bad) {
|
|
t.Fatalf("verify bytes should fail for tampered sum")
|
|
}
|
|
|
|
if tc.verifyStr(msg, key, "not-hex") {
|
|
t.Fatalf("verify hex should fail for invalid hex")
|
|
}
|
|
if tc.verify([]byte("wrong-msg"), key, sum) {
|
|
t.Fatalf("verify bytes should fail for wrong message")
|
|
}
|
|
})
|
|
}
|
|
}
|