hash.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package fingerprint
  4. import (
  5. "crypto"
  6. "errors"
  7. "strings"
  8. )
  9. var errInvalidHashAlgorithm = errors.New("fingerprint: invalid hash algorithm")
  10. func nameToHash() map[string]crypto.Hash {
  11. return map[string]crypto.Hash{
  12. "md5": crypto.MD5, // [RFC3279]
  13. "sha-1": crypto.SHA1, // [RFC3279]
  14. "sha-224": crypto.SHA224, // [RFC4055]
  15. "sha-256": crypto.SHA256, // [RFC4055]
  16. "sha-384": crypto.SHA384, // [RFC4055]
  17. "sha-512": crypto.SHA512, // [RFC4055]
  18. }
  19. }
  20. // HashFromString allows looking up a hash algorithm by it's string representation
  21. func HashFromString(s string) (crypto.Hash, error) {
  22. if h, ok := nameToHash()[strings.ToLower(s)]; ok {
  23. return h, nil
  24. }
  25. return 0, errInvalidHashAlgorithm
  26. }
  27. // StringFromHash allows looking up a string representation of the crypto.Hash.
  28. func StringFromHash(hash crypto.Hash) (string, error) {
  29. for s, h := range nameToHash() {
  30. if h == hash {
  31. return s, nil
  32. }
  33. }
  34. return "", errInvalidHashAlgorithm
  35. }