R/RSA.R

Defines functions RSAkeyGen RSA.Encrypt RSA.Decrypt

#
# Henry samuelson 11/2/17
#
# RSA
#
#' @examples
#' RSA.Decrypt(RSA.Encrypt(2198, publicKey = publicKey), privateKey = privateKey)
#
# How it works (From wiki):
# RSA (Rivest–Shamir–Adleman) is one of the first practical public-key cryptosystems
# and is widely used for secure data transmission. In such a cryptosystem, the
# encryption key is public and it is different from the decryption key which is kept
# secret (private). In RSA, this asymmetry is based on the practical difficulty of
# the factorization of the product of two large prime numbers, the "factoring problem"

#load and install required packages if they are not installed.
if (!require("numbers")) install.packages("numbers")
if (!require("gmp")) install.packages("gmp")

library(numbers)
library(gmp)

#RSAKeyGen() will generate a public and private key. Each time the funciton is run the keys will be different.
#For inputs it defaults to 61, and 53 which should be kept secret, and have to be prime. RSAKeyGen() generates e
#each time. RSAKeyGen() almost always will have a new output.

RSAkeyGen <- function(
  p = 61,
  q = 53) { #P and Q are two input primes that need to be hidden.
  library(numbers)
  library(gmp)
  n = q*p
  #n
  #The totient will be the least common factor of the factors - 1
  totient <- LCM(q-1, p-1) #Also known as Eluers Function


  e <- 17 # e has to to be co prome with totient
  #This will generate a random e value each time that will be valiad and coPrime with the totient.
  e <- numeric()
  coPrime.T <- T
  while(coPrime.T) {
    ran.int <- floor(runif(1, 0, totient))
    if(coprime(totient, ran.int)){
      coPrime.T <- F
      e <- ran.int
    }
  }

  #euler Metheod
  # (d * e) %% totient = 1
  # We have to satisfy the equation ebove using eulers method.
  for (x in 1:1000000){
    if ((1+x*totient)%%e == 0 && isprime((1+x*totient)/e)==0 ){
      d <<- (1+x*totient)/e
      if (isprime(d) != 0){
        return("d is prime, Error") #If d is prime we need a different e
      }
      break
    }
  }
  #these will appear as public vars
  publicKey <<- list(n, e) #For others to encrypt messages to you
  privateKey <<- list(n, d) #Must be kept hidden, only for the user

}

message <- 1234 #Up to four digits if more the program breaks

RSA.Encrypt <- function(message, publicKey) { #Takes a number and the public key generated by RSAKeyGen()
  library(numbers)
  library(gmp)
  n1 <- publicKey[[1]] #Reading from list
  e1 <- publicKey[[2]]

  #appy the function: message^e %% totient
  return(as.integer(mod.bigz(as.bigz(pow.bigz(message, e1)), n1)))
}
RSA.Decrypt <- function(message.Rescived, privateKey){
  library(numbers)
  library(gmp)
  n1 <- privateKey[[1]]
  d1 <- privateKey[[2]]
  #apply the function: EncryptedMessage^d mod totient
  return(as.integer(mod.bigz(as.bigz(pow.bigz(message.Rescived, d1)), n1)))
}
hsamuelson/CiphR documentation built on April 5, 2020, 4:31 p.m.