how are objects treated by crypto-js' MD5-function (https://www.npmjs.com/package/crypto-js)? I am trying to replicate the hashing behaviour in Golang using the crypto/md5 (https://pkg.go.dev/crypto/md5) package, but I can't figure out why the hashes are different for my two implementations. It must be something with how crypto-js is treating objects internally, because for pure strings I am getting the same hashes.
Node.js example:
var CryptoJS = require("crypto-js");
let body = {"key":"value"}
let bodyHash = CryptoJS.MD5(body);
CryptoJS.enc.Base64.stringify(hash)
Outputs the hash: SH97IvaDEtLBu8k7GupEWw==
Golang example:
import (
"crypto/md5"
"encoding/base64"
)
type KeyValue struct {
Key string `json:"key"`
}
func main() {
body := KeyValue{
Key: "value",
}
bodyByteArray, _ := json.Marshal(body)
bodyHash := md5.Sum(bodyByteArray)
bodyHashBase64 := base64.StdEncoding.EncodeToString(bodyHash)
}
Outputs the hash: pzU/fN3OgI3gAydHoLe+UA==
Any help and explanations are appreciated!
You are using md5 on an object not a string (you are hashing different things)
var CryptoJS = require("crypto-js");
let body = {"key":"value"}
let bodyHash = CryptoJS.MD5(JSON.stringify(body)); <<<<<<<<<
CryptoJS.enc.Base64.stringify(hash)
Hash: pzU/fN3OgI3gAydHoLe+UA==
For golang
package main
import (
"crypto/md5"
"encoding/base64"
"encoding/json"
"fmt"
)
type KeyValue struct {
Key string `json:"key"`
}
func main() {
body := KeyValue{
Key: "value",
}
bodyByteArray, _ := json.Marshal(body)
fmt.Println(string(bodyByteArray))
digest := md5.New()
digest.Write(bodyByteArray)
bodyHash := digest.Sum(nil)
bodyHashBase64 := base64.StdEncoding.EncodeToString(bodyHash)
fmt.Println(bodyHashBase64)
}
Hash: pzU/fN3OgI3gAydHoLe+UA==