SHA256 hash from struct

Hello, I have a struct that outputs two math/big numbers, e.g. {111169861534908786450528219480688090365166902692935576283050714991761558678040 88379901547641513630174298532615870317238075620523861278786581687498037788537}.
I need to get the SHA256 hash of this struct. I saw several examples online, but I didn’t find any that produces reliable results without importing external libraries. Can someone help me with this? Thanks

2 Likes

SHA256 is calculated over a sequence of bytes. You’ll have to decide how you want to encode your numbers and then calculate the hash over the result of that encoding.

2 Likes

Ok so I tried the following

h := sha256.New()
s := fmt.Sprintf("%v", struct)
sum := h.Sum([]byte(s))
fmt.Println(sum)

but the result looks like

[123 51 49 54 54 49 57 54 54 52 49 48 49 49 55 54 52 57 57 53 56 50 54 56 48 51 53 52 51 57 50 52 52 48 49 54 50 54 48 55 54 51 51 49 56 57 55 49 50 48 55 57 57 57 48 54 50 57 55 52 55 53 51 54 48 52 54 53 55 52 51 
55 55 56 48 53 52 52 32 51 54 52 50 50 49 56 56 55 54 54 55 57 57 51 52 55 55 57 49 54 54 51 53 57 56 56 56 56 56 50 56 52 56 48 52 50 51 53 55 57 52 56 53 49 55 48 54 57 57 52 53 51 49 51 56 56 55 49 53 57 56 50 49 52 54 50 48 50 52 54 51 56 52 54 54 49 125 227 176 196 66 152 252 28 20 154 251 244 200 153 111 185 36 39 174 65 228 100 155 147 76 164 149 153 27 120 82 184 85]

which is an array of unsigned integers…

2 Likes

Strictly speaking, it’s a slice of bytes ([]byte).

Also Sum() doesn’t work like that. h is a writer, where you write your data to, and at the end you call h.Sum(nil) (yes I don’t like that interface as well) to get your 32 byte long hash.

This you can then encode base16 to get the 64 char string you are used to.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.