From 191bfcc1111c0250d819eda1e90c2d514e8afc4a Mon Sep 17 00:00:00 2001
From: Johan de Klerk <johan@shiplogic.com>
Date: Mon, 17 Apr 2023 09:26:37 +0200
Subject: [PATCH] Generate hash from object function

---
 encryption/encryption.go | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)

diff --git a/encryption/encryption.go b/encryption/encryption.go
index cda03b4..2a0dfc0 100644
--- a/encryption/encryption.go
+++ b/encryption/encryption.go
@@ -1,6 +1,7 @@
 package encryption
 
 import (
+	"bytes"
 	"crypto/aes"
 	"crypto/cipher"
 	"crypto/hmac"
@@ -21,6 +22,24 @@ func Hash(input string, key string) string {
 	return base64.StdEncoding.EncodeToString(h.Sum(nil))
 }
 
+// GenerateHashFromObject using HMAC with SHA-256
+func GenerateHashFromObject(obejct any, secret string) (string, error) {
+	// Base64 Encode body
+	var buf bytes.Buffer
+	encoder := base64.NewEncoder(base64.StdEncoding, &buf)
+	defer encoder.Close()
+
+	err := json.NewEncoder(encoder).Encode(obejct)
+	if err != nil {
+		return "", err
+	}
+	encodedBody := buf.String()
+
+	// Sign encoded body with secret
+	hashedObject := Hash(encodedBody, secret)
+	return hashedObject, nil
+}
+
 func Md5HashString(bytesToHash []byte) string {
 	hash := md5.Sum(bytesToHash)
 	hashString := fmt.Sprintf("%X", hash)
-- 
GitLab