Last chance! 50% off unlimited learning
Sale ends in
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)
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.
an object.
(optional) supply a secret key to generate an HMAC. If missing or NULL, the SHA-256/224/384/512 hash of 'x' is returned.
[default TRUE] logical value whether to convert the output to a character string or keep as a raw vector.
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.
# SHA-256 hash as character string:
sha256("hello world!")
# SHA-256 hash as raw vector:
sha256("hello world!", convert = FALSE)
# Obtain HMAC:
sha256("hello world!", "SECRET_KEY")
# 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)
close(con)
unlink(tempfile)
# SHA-224 hash:
sha224("hello world!")
# SHA-384 hash:
sha384("hello world!")
# SHA-512 hash:
sha512("hello world!")
Run the code above in your browser using DataLab