Sha256 Hashes in Lua

Here’s the translation of the SHA256 Hashes example to Lua, formatted in Markdown suitable for Hugo:

-- Lua doesn't have built-in SHA256 functionality, so we'll use a third-party library
-- You can install it using LuaRocks: luarocks install sha2
local sha2 = require("sha2")

local function main()
    local s = "sha256 this string"

    -- Create a new SHA256 hash object
    local h = sha2.sha256()

    -- Update the hash with the input string
    h:update(s)

    -- Finalize the hash and get the result
    local bs = h:final()

    print(s)
    print(bs)
end

main()

SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in Lua.

Lua doesn’t have built-in cryptographic functions, so we need to use a third-party library. In this example, we’re using the sha2 library, which you can install using LuaRocks:

luarocks install sha2

We start by requiring the sha2 library:

local sha2 = require("sha2")

In the main function, we define our input string:

local s = "sha256 this string"

Then we create a new SHA256 hash object:

local h = sha2.sha256()

We update the hash with our input string:

h:update(s)

Finally, we finalize the hash and get the result:

local bs = h:final()

We then print both the original string and the hash:

print(s)
print(bs)

Running the program computes the hash and prints it:

$ lua sha256-hashes.lua
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0639b9d9a17bcc3

Note that the exact output format might differ depending on the specific SHA256 library you’re using. Some libraries might return the hash as a hexadecimal string by default, while others might return it as raw bytes.

If you need to use other hash functions, you can check if your chosen cryptographic library supports them. For example, the sha2 library also supports SHA512 hashes.

Remember, if you need cryptographically secure hashes, you should carefully research hash strength!