Returns a SHA-3 hash of the supplied R object or file.

sha3(x, bits = 256L, convert = TRUE, file)

Arguments

x

R object to hash. A character string or raw vector (without attributes) is hashed 'as is'. All other objects are hashed using R serialization in a memory-efficient 'streaming' manner, without allocation of the serialized object. To ensure portability, serialization v3 XDR is always used with headers skipped (as these contain R version and encoding information).

bits

[default 256L] output size of the returned hash. If one of 224, 256, 384 or 512, uses the relevant SHA-3 cryptographic hash function. For all other values, uses the SHAKE256 extendable-output function (XOF). Must be between 8 and 2^24 and coercible to integer.

convert

[default TRUE] if TRUE, the hash is converted to its hex representation as a character string, if FALSE, output directly as a raw vector, or if NA, a vector of (32-bit) integer values.

file

character file name / path. If specified, 'x' is ignored. The file is hashed in a streaming fashion and may be larger than memory.

Value

A character string, raw or integer vector depending on 'convert'.

Details

To produce single integer values suitable for use as random seeds for R's pseudo random number generators (RNGs), set 'bits' to 32 and 'convert' to NA.

Examples

# SHA3-256 hash as character string:
sha3("secret base")
#> [1] "a721d57570e7ce366adee2fccbe9770723c6e3622549c31c7cab9dbb4a795520"

# SHA3-256 hash as raw vector:
sha3("secret base", convert = FALSE)
#>  [1] a7 21 d5 75 70 e7 ce 36 6a de e2 fc cb e9 77 07 23 c6 e3 62 25 49 c3 1c 7c
#> [26] ab 9d bb 4a 79 55 20

# SHA3-224 hash as character string:
sha3("secret base", bits = 224)
#> [1] "5511b3469d3f1a87b62ce8f0d2dc9510ec5e4547579b8afb32052f99"

# SHA3-384 hash as character string:
sha3("secret base", bits = 384)
#> [1] "79e54f865df004dde10dc2f61baf47eb4637c68d87a2baeb7fe6bc0ac983c2154835ec7deb49b16c246c0dc1d43e32f9"

# SHA3-512 hash as character string:
sha3("secret base", bits = 512)
#> [1] "31076b4690961320a761be0951eeaa9efd0c75c37137a2a50877cbebb8afcc6d7927c41a120ae8fa73fdce8fff726fcbc51d448d020240bc7455963a16e639b1"

# SHAKE256 hash to integer:
sha3("secret base", bits = 32L, convert = NA)
#> [1] -1044750695

# SHA3-256 hash a file:
file <- tempfile(); cat("secret base", file = file)
sha3(file = file)
#> [1] "a721d57570e7ce366adee2fccbe9770723c6e3622549c31c7cab9dbb4a795520"
unlink(file)