Skip to content

Commit

Permalink
Add fingerprint.StringFromHash
Browse files Browse the repository at this point in the history
Inverse function of fingerprint.HashFromString.
  • Loading branch information
at-wat committed Feb 6, 2020
1 parent 51c3deb commit dca3dfb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkg/crypto/fingerprint/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
16 changes: 16 additions & 0 deletions pkg/crypto/fingerprint/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

0 comments on commit dca3dfb

Please sign in to comment.