R/eruu_generate_keys.R

Defines functions digest_passwd encrypt_redcap_key decrypt_redcap_key

Documented in decrypt_redcap_key digest_passwd encrypt_redcap_key

#' Digests/hash the password using the sha512 algorithm and returns the sodium
#' hash required to sodium encryption
#' @param passwd the password to hash
#'
#' @return the hashed password
#'
#' Do no export
digest_passwd <- function(passwd){
  passwd <- charToRaw(passwd)
  return(sodium::hash(passwd, size = 32))
}

#' encrypts a redcap key (or any character message) using a password and returns
#' the character of the encrypted key
#'
#' @param passwd the passwd to use as a base of the encryption
#' @param redcap_key the character string to encrypt
#'
#' @return the encrypted key as a character
#'
#' @export
encrypt_redcap_key <- function(passwd, redcap_key){
  key <- digest_passwd(passwd)
  pub <- sodium::pubkey(key)
  msg <- charToRaw(redcap_key)
  cipher <- sodium::simple_encrypt(msg, pub)
  return(cipher)
}

#' decrypts a redcap key (or any character message) using a password and returns
#' the character of the decrypted key
#'
#' @param passwd the passwd to use as a base of the encryption
#' @param cipher the character string to decrypt
#'
#' @return the decrypted key as a character
#'
#' @export
decrypt_redcap_key <- function(passwd, cipher){
  key <- digest_passwd(passwd)
  tryCatch({
      return(rawToChar(sodium::simple_decrypt(cipher, key)))
    },
    error = function(e){return(NULL)}
  )
}
pydupont/esr.redcap.user.ui documentation built on Dec. 25, 2019, 3:20 a.m.