danielga / gm_crypt

A cryptography module for the game Garry's Mod that uses Crypto++.
https://github.com/danielga/gm_crypt
Other
13 stars 3 forks source link

How do I actually use this module? #4

Closed viral32111 closed 4 years ago

viral32111 commented 4 years ago

There's so little documentation available for this module, all I could find was a reference to the SHA1 in this websocket module by you. So far I've got this code:

require("crypt")
local sha256hasher = crypt.SHA256()
local hashedValue = sha256hasher:CalculateDigest("test")
print(hashedValue)

However this outputs a bunch of garbage bytes along the lines of ЁL}e/ZO+ ,]l

I'm trying to get the SHA256 hash of test, which according to this website is 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08.

Can someone please explain how to use this module or at the very least just how to simply SHA256 hash a string?

viral32111 commented 4 years ago

Never mind, In all my time of using hashes and researching cryptography apparently I never once realised that a hash is actually a hexadecimal string. Every other high-level hash library in other languages seems to automatically do this for you and never before have I ever came across a time where I had to manually convert the output bytes to hex.

I made this quick function which works exactly as expected:

function hex(original)
    local hex = ""
    for i = 1, #original do
        hex = hex .. string.format('%02X', string.byte(string.sub(original, i, i)))
    end
    return hex
end

Now the script:

local hasher = crypt.SHA256()
local myHash = hasher:CalculateDigest(myString)
print(string.lower(hex(myHash)))

outputs 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 just like I originally wanted.

Hope this helps anyone in the future who is having the same issues as me.