HMAC-SHA256 in GDscript

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Montecri

Hello all,

Trying to connect to GameAnalytics REST API from a game I’m building, but HMAC-SHA256 is mandatory and, since I couldn’t find a built-in function in GDscript, I’m trying to implement myself. When done, will be a true cross-platform solution for game analytics, no engine recompiling and stuff.

However, tried to no avail and the hash result I get differ from the expected result find in sites like Free Online HMAC Generator / Checker Tool (MD5, SHA-256, SHA-512) - FreeFormatter.com

Tried several HMAC-SHA256 generators and they all produce the same output, the bug is in my code.

Data I’m using:

Key: 0123456789012345678901234567890123456789012345678901234567890123
Message: 0123456789012345678901234567890123456789012345678901234567890123ABCD

Using a fixed length key to debug for now.

What I’m doing wrong ??

Code below.

Yes, the code is redundant, ugly, crazy, etc; it’s a mix of trying to pinpoint where it went wrong with my recent (1 week) acquired GDscript skills.


func hmac(key, message):
var x = 0
var i = “”.to_ascii()
var o = “”.to_ascii()
var m = message.to_ascii()
var k = key.to_ascii()
var s = File.new()

while x < 64:
	o.append(k[x] ^ 0x5c)
	x += 1
	
x = 0
while x < 64:
	i.append(k[x] ^ 0x36)
	x += 1

var temp1 = i + m

s.open("user://s.save", File.WRITE)
s.store_buffer(temp1)
s.close()
var z = s.get_sha256("user://s.save")
var temp2  = z.to_ascii()

var temp3 = o + temp2

s.open("user://s.save", File.WRITE)
s.store_buffer(temp3)
s.close()

z = s.get_sha256("user://s.save")

return z

SUCCESS!!

Managed to fix all. See here:

GitHub - Montecri/Godot-GameAnalytics: Native GDScript for GameAnalytics in Godot

Montecri | 2018-04-25 19:54

:bust_in_silhouette: Reply From: Brandon Lamb

Just a peanut gallery comment that perhaps this would make a cool gdnative addon written in c++

Hi!

Implemented it myself in GDScript. Check here:

GitHub - Montecri/Godot-GameAnalytics: Native GDScript for GameAnalytics in Godot

Montecri | 2018-04-25 19:47

:bust_in_silhouette: Reply From: tavurth

I found this library which performs the task for 3.1: