Learn R Programming

nanonext (version 0.7.2)

sha256: Cryptographic Hashing Using the SHA-2 Algorithms

Description

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.

Usage

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

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

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

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

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.

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. Supplying a non-logical value will error.

Details

For arguments 'x' and 'key', a raw vector is hashed directly, a scalar character string is translated to raw before hashing, whilst all other objects are serialised first.

The result of hashing is always a raw vector, which is translated to a character string if 'convert' is TRUE, or returned directly if 'convert' is FALSE.

Examples

Run this code
# 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