Returns a SHA-256, SHA-224, SHA-384, or SHA-512 hash or HMAC of the supplied R object. Uses the optimised implementation from the Mbed TLS library.

sha256(x, key = NULL, convert = TRUE)

sha224(x, key = NULL, convert = TRUE)

sha384(x, key = NULL, convert = TRUE)

sha512(x, key = NULL, convert = TRUE)

Arguments

x

an object.

key

(optional) supply a secret key to generate an HMAC. If missing or NULL, the SHA-256/224/384/512 hash of 'x' is returned.

convert

[default TRUE] logical value whether to convert the output to a character string or keep as a raw vector.

Value

A raw vector or character string depending on 'convert', of byte length 32 for SHA-256, 28 for SHA-224, 48 for SHA-384, and 64 for SHA-512.

Details

For arguments 'x' and 'key', a scalar string or raw vector (with no attributes) is hashed 'as is'.

All other objects are first serialized using R serialization v3 XDR, with headers skipped (for portability as these contain R version and encoding information).

The result of hashing is always a byte sequence, which is converted to a character string hex representation if 'convert' is TRUE, or returned as a raw vector if 'convert' is FALSE.

Examples

# SHA-256 hash as character string:
sha256("hello world!")
#> [1] "7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9"

# SHA-256 hash as raw vector:
sha256("hello world!", convert = FALSE)
#>  [1] 75 09 e5 bd a0 c7 62 d2 ba c7 f9 0d 75 8b 5b 22 63 fa 01 cc bc 54 2a b5 e3
#> [26] df 16 3b e0 8e 6c a9

# Obtain HMAC:
sha256("hello world!", "SECRET_KEY")
#> [1] "7fb67726fa6dd05104b502910649cb7ae354a1d674400d7b12b5a5bbf3982695"

# Hashing a file:
tempfile <- tempfile()
cat(rep(letters, 256), file = tempfile)
con <- file(tempfile, open = "rb")
vec <- NULL
while (length(upd <- readBin(con, raw(), 8192))) vec <- c(vec, upd)
sha256(vec)
#> [1] "a575e36487c8c13dd19da60a1077d2c10ec8a5ccd2e5eedb17802bcd4097f545"
close(con)
unlink(tempfile)

# SHA-224 hash:
sha224("hello world!")
#> [1] "428c16b4309e824cfa874fe24ce2af2894fcaf8d72af4a368d492e34"

# SHA-384 hash:
sha384("hello world!")
#> [1] "d33d40f7010ce34aa86efd353630309ed5c3d7ffac66d988825cf699f4803ccdf3f033230612f0945332fb580d8af805"

# SHA-512 hash:
sha512("hello world!")
#> [1] "db9b1cd3262dee37756a09b9064973589847caa8e53d31a9d142ea2701b1b28abd97838bb9a27068ba305dc8d04a45a1fcf079de54d607666996b3cc54f6b67c"