commit f008bc556e01622f975f19ddd9db29abdba5038b
parent e0291d931af4363aae9b268bbe3909f69e3c192a
Author: Shivakumar <[email protected]>
Date: Mon, 8 Jun 2026 14:30:10 +0530
feat(crypto): functions now return hex representation
Signed-off-by: Shivakumar <[email protected]>
Diffstat:
1 file changed, 32 insertions(+), 0 deletions(-)
diff --git a/internal/crypto/hash.go b/internal/crypto/hash.go
@@ -17,7 +17,10 @@ package crypto
import (
"crypto/sha256"
"encoding/binary"
+ "encoding/hex"
+ "encoding/json"
"errors"
+ "fmt"
)
const (
@@ -76,3 +79,32 @@ func HashCanonical(fields ...[]byte) (Hash, error) {
return HashBytes(canonical), nil
}
+
+// String returns the hex representation of the hash.
+func (h Hash) String() string {
+ return hex.EncodeToString(h[:])
+}
+
+// MarshalJSON encodes the hash as a hex string for JSON.
+func (h Hash) MarshalJSON() ([]byte, error) {
+ return json.Marshal(h.String())
+}
+
+// UnmarshalJSON decodes a hex string into a Hash.
+func (h *Hash) UnmarshalJSON(data []byte) error {
+ var s string
+ if err := json.Unmarshal(data, &s); err != nil {
+ return err
+ }
+
+ decoded, err := hex.DecodeString(s)
+ if err != nil {
+ return err
+ }
+ if len(decoded) != HashSize {
+ return fmt.Errorf("crypto: invalid hash length: excepted = %d, got = %d", HashSize, len(decoded))
+ }
+ copy(h[:], decoded)
+
+ return nil
+}