autokey <- function(plain="", cipher="", keyletter="A") { # 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(cipher)) { # encode plaintext plain <- toupper(plain) keyletter <- toupper(keyletter) textlen <- nchar(plain) alphanum <- 1:26 cipher <- " " for(i in 2:textlen) { cipher <- paste(cipher, " ", sep="") } currkey <- keyletter for(i in 1:textlen) { currletter <- substring(plain, i, i) if(currletter != " ") { 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) } } } if(missing(plain)) { # decode ciphertext cipher <- toupper(cipher) keyletter <- toupper(keyletter) textlen <- nchar(cipher) alphanum <- 1:26 plain <- " " for(i in 2:textlen) { plain <- paste(plain, " ", sep="") } currkey <- keyletter for(i in 1:textlen) { currletter <- substring(cipher, i, i) if(currletter != " ") { 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) } } } list(plain=plain, cipher=cipher, keyletter=keyletter) }