Sha256 Hashes in R Programming Language

Here’s the translation of the SHA256 Hashes example from Go to R, formatted in Markdown suitable for Hugo:

SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in R.

# R implements several hash functions in various packages.
# We'll use the 'digest' package for SHA256 hashing.
library(digest)

# Define our main function
main <- function() {
  s <- "sha256 this string"
  
  # In R, we can directly use the sha256 function from the digest package
  hash <- digest(s, algo = "sha256", serialize = FALSE)
  
  # Print the original string and its hash
  cat(s, "\n")
  cat(hash, "\n")
}

# Call the main function
main()

Running the program computes the hash and prints it in a human-readable hex format.

$ Rscript sha256_hashes.R
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

You can compute other hashes using similar functions from the digest package. For example, to compute SHA512 hashes, you can use digest(s, algo = "sha512", serialize = FALSE).

Note that if you need cryptographically secure hashes, you should carefully research hash strength!

In R, we use the digest package to perform cryptographic hashing. This package provides a simple interface to various hashing algorithms, including SHA256. Unlike the Go example where we needed to create a new hash, write to it, and then sum it, in R we can directly hash our string in one function call.

The digest function takes several arguments:

  • The object to be hashed (in our case, the string)
  • The algorithm to use ("sha256" in this case)
  • serialize = FALSE to treat the input as a raw string rather than serializing it first

Remember to install the digest package before running this script, using install.packages("digest").