wordkey <- function(plain="", cipher="", keyword) { # encode or decode an autokey cipher if(missing(plain) && missing(cipher)) { stop("Must include one of plaintext or ciphertext!") } if(!missing(plain) && !missing(cipher)) { stop("Included both plaintext and ciphertext!") } if(missing(keyword)) keyword <- paste(LETTERS, sep="", collapse="") keyword <- toupper(keyword) if(missing(cipher)) { # encode plaintext plain <- toupper(plain) textlen <- nchar(plain) alphanum <- 1:26 ## set up keyword longkey <- paste(rep(0, textlen), sep="", collapse="") # remove spaces strindex <- 1 for(i in 1:textlen) { while(is.na(any(match(LETTERS, substring(keyword, strindex, strindex))))) { strindex <- strindex + 1 if(strindex > nchar(keyword)) strindex <- 1 } substring(longkey, i, i) <- substring(keyword, strindex, strindex) strindex <- strindex + 1 if(strindex > nchar(keyword)) strindex <- 1 } cipher <- paste(rep(0, textlen), sep="", collapse="") strindex <- 1 for(i in 1:textlen) { currletter <- substring(plain, i, i) if(currletter != " ") { currkey <- substring(longkey, strindex, strindex) strindex <- strindex + 1 currkey <- alphanum[!is.na(match(LETTERS, currkey))] - 1 currletter <- alphanum[!is.na(match(LETTERS, currletter))] currletter <- currletter + currkey if(currletter > 26) { currletter <- currletter - 26 } currletter <- LETTERS[currletter] substring(cipher, i, i) <- currletter currkey <- substring(plain, i, i) } else { substring(cipher, i, i) <- " " } } } if(missing(plain)) { # decode ciphertext cipher <- toupper(cipher) textlen <- nchar(cipher) alphanum <- 1:26 ## set up keyword longkey <- paste(rep(0, textlen), sep="", collapse="") # remove spaces strindex <- 1 for(i in 1:textlen) { while(is.na(any(match(LETTERS, substring(keyword, strindex, strindex))))) { strindex <- strindex + 1 if(strindex > nchar(keyword)) strindex <- 1 } substring(longkey, i, i) <- substring(keyword, strindex, strindex) strindex <- strindex + 1 if(strindex > nchar(keyword)) strindex <- 1 } plain <- paste(rep(0, textlen), sep="", collapse="") strindex <- 1 for(i in 1:textlen) { currletter <- substring(cipher, i, i) if(currletter != " ") { currkey <- substring(longkey, strindex, strindex) strindex <- strindex + 1 currkey <- alphanum[!is.na(match(LETTERS, currkey))] - 1 currletter <- alphanum[!is.na(match(LETTERS, currletter))] currletter <- currletter - currkey if(currletter < 1) { currletter <- currletter + 26 } currletter <- LETTERS[currletter] substring(plain, i, i) <- currletter currkey <- substring(plain, i, i) } else { substring(plain, i, i) <- " " } } } list(plain=plain, cipher=cipher, keyword=keyword) }