### 36.12 Hashing Functions ¶

It is often necessary to find if two strings or files are identical. This might be done by comparing them character by character and looking for differences. However, this can be slow, and so comparing a hash of the string or file can be a rapid way of finding if the files differ.

Another use of the hashing function is to check for file integrity. The user can check the hash of the file against a known value and find if the file they have is the same as the one that the original hash was produced with.

Octave supplies the `hash` function to calculate hash values of strings and files, the latter in combination with the `fileread` function. The `hash` function supports many commonly used hash methods.

`hashval =` hash `("hashfcn", str)` ¶

  Calculate the hash value of the string str using the hash function hashfcn.

  The available hash functions are given in the table below.

  ‘`MD2`’

    Message-Digest Algorithm 2 (RFC 1319).

  ‘`MD4`’

    Message-Digest Algorithm 4 (RFC 1320).

  ‘`MD5`’

    Message-Digest Algorithm 5 (RFC 1321).

  ‘`SHA1`’

    Secure Hash Algorithm 1 (RFC 3174)

  ‘`SHA224`’

    Secure Hash Algorithm 2 (224 Bits, RFC 3874)

  ‘`SHA256`’

    Secure Hash Algorithm 2 (256 Bits, RFC 6234)

  ‘`SHA384`’

    Secure Hash Algorithm 2 (384 Bits, RFC 6234)

  ‘`SHA512`’

    Secure Hash Algorithm 2 (512 Bits, RFC 6234)

  To calculate for example the MD5 hash value of the string `"abc"` the `hash` function is called as follows:

      hash ("md5", "abc")
           ⊣ ans = 900150983cd24fb0d6963f7d28e17f72

  For the same string, the SHA-1 hash value is calculated with:

      hash ("sha1", "abc")
           ⊣ ans = a9993e364706816aba3e25717850c26c9cd0d89d

  And to compute the hash value of a file, e.g., `file = "file.txt"`, call `hash` in combination with the `fileread`:

      hash ("md5", fileread (file));