A Lua Implemention of the SHA-1 Hashing Function

With the code provided below, you can easily create a new module that provides a Lua implementation of the common SHA-1 hashing algorithm. To create and access this module, you will have to perform the following steps:

  1. In the Translator, create a new module called “sha1”. The new module is added to the shared list:
  2. Click on the new module to open its contents in the Editor (the page should be blank).
  3. Copy and paste the code from the bottom of this page into the Editor, populating the module.
  4. Return to your own script by clicking on main.
  5. Add the line require ("sha1") to the top of your script. This loads the new module that you’ve just created, allowing you to access its functions for use in your script.
  6. Commit a milestone to save your work.

How Does It Work?

In the most simplest terms, the sha1 module is a Lua implementation of the common SHA-1 hashing algorithm. For example, the following code snippet demonstrates how to produce the hexadecimal representation of the SHA-1 hash for the string “iNTERFACEWARE”.

The module also contains a function for generating the 160-bit binary representation of the hash. Lua itself does not contain a built-in binary value, so these are still represented as strings. You can also generate hash-based message authentication codes (HMACs) using the module by providing a cryptographic key.

Versions of Lua 5.1 and earlier do not contain direct access to common bitwise operators (such as bitwise AND and OR), so the module must generate these on-the-fly. This can be done in two ways: all results needed by the algorithm can be generated at script compile-time, or these can be generated dynamically as the algorithm progresses. The method used is controlled through the cfg_caching variable defined near the top of the sha1 module code. By default, we have set this “caching” to be disabled when the script is being edited in the Translator, as it can cause auto-completion and annotations to become sluggish. However, when the channel is run, this cache will be generated ahead of time, resulting in better overall performance when your script is generating several SHA-1 hashes in a row.

Download the code for this module from our code repository. Notice the extensive comments included in the code, to help you better understand the purpose of its functions. 

For Example:

See also:

Leave A Comment?