Returns a SHA-256 hash of the supplied object or file, or HMAC if a secret key is supplied.

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

Arguments

x

object to hash. A character string or raw vector (without attributes) is hashed 'as is'. All other objects are stream hashed using R serialization, but without requiring allocation of the serialized object. To ensure portability, serialization version 3 big-endian represenation is always used with headers skipped (as these contain R version and native encoding information).

key

[default NULL] If NULL, the SHA-256 hash of 'x' is returned. Alternatively, supply a secret key as a character string or raw vector to generate an HMAC. Note: for character vectors only the first element is used.

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 stream hashed, thus capable of handling files larger than memory.

Value

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

Details

The SHA-256 Secure Hash Standard was published by the National Institute of Standards and Technology (NIST) in 2002 at https://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf.

This implementation is based on one by 'The Mbed TLS Contributors' under the 'Mbed TLS' Trusted Firmware Project at https://www.trustedfirmware.org/projects/mbed-tls.

Examples

# SHA-256 hash as character string:
sha256("secret base")
#> [1] "1951c1ca3d50e95e6ede2b1c26fefd0f0e8eba1e51a837f8ccefb583a2b686fe"

# SHA-256 hash as raw vector:
sha256("secret base", convert = FALSE)
#>  [1] 19 51 c1 ca 3d 50 e9 5e 6e de 2b 1c 26 fe fd 0f 0e 8e ba 1e 51 a8 37 f8 cc
#> [26] ef b5 83 a2 b6 86 fe

# SHA-256 hash a file:
file <- tempfile(); cat("secret base", file = file)
sha256(file = file)
#> [1] "1951c1ca3d50e95e6ede2b1c26fefd0f0e8eba1e51a837f8ccefb583a2b686fe"
unlink(file)

# SHA-256 HMAC using a character string secret key:
sha256("secret", key = "base")
#> [1] "14b24e4c66bd03c1d6b59bc59e1e47468a437001662ae4be2cb30e0483e13e44"

# SHA-256 HMAC using a raw vector secret key:
sha256("secret", key = charToRaw("base"))
#> [1] "14b24e4c66bd03c1d6b59bc59e1e47468a437001662ae4be2cb30e0483e13e44"