sodium (version 1.0)

Hash functions: Hash Functions

Description

Functions to calculate cryptographic hash of a message, with optionally a key for HMAC applications. For storing passwords, use password_store instead.

Usage

hash(buf, key = NULL, size = 32)

scrypt(buf, salt = raw(32), size = 32)

shorthash(buf, key)

sha512(buf, key = NULL)

sha256(buf, key = NULL)

Arguments

buf
data to be hashed
key
key for HMAC hashing. Optional, except for in shorthash.
size
length of the output hash. Must be between 16 and 64 (recommended is 32)
salt
non-confidential random data to seed the algorithm

Details

The generic hash function is recommended most most applications. It uses dynamic length https://download.libsodium.org/doc/hashing/generic_hashing.html where output size can be any value between 16 bytes (128bit) and 64 bytes (512bit). The scrypt hash function is designed to be CPU and memory expensive to protect against brute force attacks. This algorithm is also used by the password_store function. The shorthash function is a special 8 byte (64 bit) hash based on https://download.libsodium.org/doc/hashing/short-input_hashing.html. The output of this function is only 64 bits (8 bytes). It is useful for in e.g. Hash tables, but it should not be considered collision-resistant. Hash functions can be used for HMAC by specifying a secret key. They key size for shorthash is 16 bytes, for sha256 it is 32 bytes and for sha512 it is 64 bytes. For hash the key size can be any value between 16 and 62, recommended is at least 32.

References

https://download.libsodium.org/doc/hashing/generic_hashing.html

Examples

Run this code
# Basic hashing
msg <- serialize(iris, NULL)
hash(msg)
sha256(msg)
sha512(msg)
scrypt(msg)

# Generate keys from passphrase
passphrase <- charToRaw("This is super secret")
key <- hash(passphrase)
shortkey <- hash(passphrase, size = 16)
longkey <- hash(passphrase, size = 64)

# HMAC (hashing with key)
hash(msg, key = key)
shorthash(msg, shortkey)
sha256(msg, key = key)
sha512(msg, key = longkey)

Run the code above in your browser using DataCamp Workspace