From dca3dfbc6acc24a116640805bc9896df7e8fc244 Mon Sep 17 00:00:00 2001 From: Atsushi Watanabe Date: Thu, 6 Feb 2020 14:07:44 +0900 Subject: [PATCH] Add fingerprint.StringFromHash Inverse function of fingerprint.HashFromString. --- pkg/crypto/fingerprint/hash.go | 10 ++++++++++ pkg/crypto/fingerprint/hash_test.go | 16 ++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/pkg/crypto/fingerprint/hash.go b/pkg/crypto/fingerprint/hash.go index 7f336b897..99e7fa51d 100644 --- a/pkg/crypto/fingerprint/hash.go +++ b/pkg/crypto/fingerprint/hash.go @@ -23,3 +23,13 @@ func HashFromString(s string) (crypto.Hash, error) { } return 0, errInvalidHashAlgorithm } + +// StringFromHash allows looking up a string representation of the crypto.Hash. +func StringFromHash(hash crypto.Hash) (string, error) { + for s, h := range nameToHash { + if h == hash { + return s, nil + } + } + return "", errInvalidHashAlgorithm +} diff --git a/pkg/crypto/fingerprint/hash_test.go b/pkg/crypto/fingerprint/hash_test.go index 1280252e3..e9617b7cd 100644 --- a/pkg/crypto/fingerprint/hash_test.go +++ b/pkg/crypto/fingerprint/hash_test.go @@ -22,3 +22,19 @@ func TestHashFromString(t *testing.T) { } }) } + +func TestStringFromHash_Roundtrip(t *testing.T) { + for _, h := range nameToHash { + s, err := StringFromHash(h) + if err != nil { + t.Fatalf("Unexpected error for valid hash algorithm, got '%v'", err) + } + h2, err := HashFromString(s) + if err != nil { + t.Fatalf("Unexpected error for valid hash name, got '%v'", err) + } + if h != h2 { + t.Errorf("Hash value doesn't match, expected: 0x%x, got 0x%x", h, h2) + } + } +}