jeudi 5 octobre 2017

Why is my if statement storing the wrong data types?

Okay, so I have combed the internet for an answer to my problem and I can only put it down to me being a little naive in how R works.

Below is my code for a function that generates public and private keys from the system clock and uses it to attempt to decrypt an encrypted message. This bit works fine, but obviously as it goes through different random generations it comes back with a lot of garbage and NULL data.

FindKey <- function(a, y) {
x <<- 1 #initialisation
decodedlist <<- list()
while (x<100) {
print(x)
print(a)
p <- nextprime(urand.bigz(size=51, seed=as.bigz(a)))
q <- nextprime(urand.bigz(size=50))
n <- p*q

phi <- (p-1) * (q-1) #  Euler's totient function; kept private
phi
e <-finde(phi) # e is the other public key
d <- inv.bigz(e, phi) # a private key

recieved<-dget(file=y)
v<-as.bigz(as.bigz(recieved, n)^d)

tryCatch({
  decodetext<-dectext(v)
  Decrypt<- capture.output(cat(decodetext))
  print(Decrypt)
  test <- grep("and", Decrypt)
  if (!is.null(Decrypt)){
  if (is.character(Decrypt)){
    decodedlist[[x]] <<- Decrypt
  }else{return}}else{return}
  }, warning = function(war) {
    return()
  }, error = function(err){
    return()
  }, finally = {
    x=x+1
  a=a-1})
}
}

I wanted to filter this out by using grep and testing whether the result of that grep was 1, is so, the decoded message would be put into a list.

The problem is that, no matter how I propose the if statement, my list gets cluttered with both the nonsense entries and the NULL entries. I've tried, !is.null, is.character. test == 1. etc etc but nothing seems to work. Either the list doesn't get populated at all, or it gets populated by every entry that runs through the if statement.

Any advice would be appreciated. Thanks :)

Aucun commentaire:

Enregistrer un commentaire