hex_bytes.go 981 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package data
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "errors"
  6. )
  7. type HexBytes []byte
  8. func (b *HexBytes) UnmarshalJSON(data []byte) error {
  9. if len(data) < 2 || len(data)%2 != 0 || data[0] != '"' || data[len(data)-1] != '"' {
  10. return errors.New("tuf: invalid JSON hex bytes")
  11. }
  12. res := make([]byte, hex.DecodedLen(len(data)-2))
  13. _, err := hex.Decode(res, data[1:len(data)-1])
  14. if err != nil {
  15. return err
  16. }
  17. *b = res
  18. return nil
  19. }
  20. func (b HexBytes) MarshalJSON() ([]byte, error) {
  21. res := make([]byte, hex.EncodedLen(len(b))+2)
  22. res[0] = '"'
  23. res[len(res)-1] = '"'
  24. hex.Encode(res[1:], b)
  25. return res, nil
  26. }
  27. func (b HexBytes) String() string {
  28. return hex.EncodeToString(b)
  29. }
  30. // 4.5. File formats: targets.json and delegated target roles:
  31. // ...each target path, when hashed with the SHA-256 hash function to produce
  32. // a 64-byte hexadecimal digest (HEX_DIGEST)...
  33. func PathHexDigest(s string) string {
  34. b := sha256.Sum256([]byte(s))
  35. return hex.EncodeToString(b[:])
  36. }