sha256: SHA-256 Cryptographic Hash Algorithm

View source: R/secret.R

sha256R Documentation

SHA-256 Cryptographic Hash Algorithm

Description

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

Usage

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 native R serialization.

key

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

convert

logical TRUE to convert the hash to its hex representation as a character string, FALSE to return directly as a raw vector, or NA to return as a vector of (32-bit) integers.

file

character file name / path. If specified, x is ignored. The file is stream hashed, and the file can be larger than memory.

Value

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

R Serialization Stream Hashing

Where this is used, serialization is always version 3 big-endian representation and the headers (containing R version and native encoding information) are skipped to ensure portability across platforms.

As hashing is performed in a streaming fashion, there is no materialization of, or memory allocation for, the serialized object.

References

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")

# SHA-256 hash as raw vector:
sha256("secret base", convert = FALSE)

# SHA-256 hash a file:
file <- tempfile(); cat("secret base", file = file)
sha256(file = file)
unlink(file)

# SHA-256 HMAC using a character string secret key:
sha256("secret", key = "base")

# SHA-256 HMAC using a raw vector secret key:
sha256("secret", key = charToRaw("base"))


secretbase documentation built on April 4, 2025, 1:34 a.m.