R/enc.R

Defines functions enc enc.Rcpp_FandV_pk

Documented in enc

#' Encrypt a message
#' 
#' This encrypts an integer message under one of the homomorphic encryption schemes
#' supported by this package.
#' 
#' The scheme to use is determined by the public key which contains the parameter
#' values for that scheme as part of it.
#' 
#' If a symmetric key scheme is being used, then the secret key should be provided
#' for the \code{pk} argument.
#' 
#' @param pk a public key for any scheme as generated by the \code{\link{keygen}}.
#' function.
#' 
#' @param m an integer to be encrypted.  Note that the permissable range of values
#' for \code{m} is dependent on the scheme and the parameters of the scheme.
#' \code{m} may even be resticted to as little as \{0,1\}, for example in binary
#' encryption schemes.
#' 
#' @return
#' A ciphertext under the encryption scheme, encrypted using the public key
#' provided.
#' 
#' @seealso
#' \code{\link{keygen}} to create public/private keypairs;
#' \code{\link{dec}} to decrypt the ciphertext generated by this function.
#' 
#' @examples
#' p <- pars("FandV")
#' keys <- keygen(p)
#' ct <- enc(keys$pk, 1)
#' dec(keys$sk, ct)
#' 
#' @author Louis Aslett
enc <- function(pk, m) {
  if(is.null(attr(pk, "FHEt")) || attr(pk, "FHEt")!="pk") stop("pk argument is not a public key.")
  UseMethod("enc", pk)
}

enc.Rcpp_FandV_pk <- function(pk, m) {
  if(!isTRUE(all.equal(round(m), m))) stop("Only integers can be encrypted.")
  
  if(is.matrix(m)) {
    ct <- new(FandV_ct_mat)
    pk$encmat(as.vector(m), nrow(m), ncol(m), ct)
    
    # Prepare return result
    attr(ct, "FHEt") <- "ctmat"
    attr(ct, "FHEs") <- "FandV"
    return(ct)
  } else if(length(m) == 1) {
    ct <- new(FandV_ct, pk$p, rlkLocker, pk$rlki)
    pk$enc(m, ct)
    
    # Prepare return result
    attr(ct, "FHEt") <- "ct"
    attr(ct, "FHEs") <- "FandV"
    return(ct)
  } else {
    ct <- new(FandV_ct_vec)
    pk$encvec(m, ct)
    
    # Prepare return result
    attr(ct, "FHEt") <- "ctvec"
    attr(ct, "FHEs") <- "FandV"
    return(ct)
  }
}

# enc.FandV_CRT_pk <- function(pk, m) {
#   if(!isTRUE(all.equal(round(m), m))) stop("Only integers can be encrypted.")
#   
#   crt <- new("CRT", ct=list(), ctvalid=c(TRUE))
#   for(i in 1:length(pk)) {
#     crt@ct[[i]] <- enc(pk[[i]], m)
#     crt@ctvalid[i] <- TRUE
#   }
#   
#   # Prepare return result
#   attr(crt, "FHEt") <- attr(crt@ct[[1]], "FHEt")
#   attr(crt, "FHEs") <- "FandV_CRT"
#   return(crt)
# }
iamtrask/R-Homomorphic-Encryption-Package documentation built on May 29, 2019, 2:56 p.m.