Learn R Programming

nanonext (version 0.13.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.

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

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