-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathexample.R
57 lines (47 loc) · 1.43 KB
/
example.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# encrypts message
encrypt <- function(message, a, b) {
m <- 26
# computes the greatest common divisor of numbers x and y
gcd <- function(x, y) {
r <- x %% y
return(ifelse(r, gcd(y, r), y))
}
# must check a and m are coprime
if (gcd(a, m) != 1) {
stop("a and 26 must be co-prime")
}
parsedMessage <- tolower(gsub(" ", "", message)) # removed whitespace & lower-cased
splitList <- strsplit(parsedMessage, "")[[1]] # list of letters
x <- match(splitList, letters) - 1 # index of letters
# E(x) = (ax + b) mod m
return(paste(letters[ ((a * x + b) %% m) + 1], collapse = ""))
}
# decrypts encryption
decrypt <- function(encryption, a, b) {
m <- 26
# computes the greatest common divisor of numbers x and y
gcd <- function(x, y) {
r <- x %% y
return(ifelse(r, gcd(y, r), y))
}
# must check a and m are coprime
if (gcd(a, m) != 1) {
stop("a and 26 must be co-prime")
}
# computes the modulo multiplicative inverse of a^m
# a^-1 = mmi( a mod m)=mmi(a,m)
mmi <- function(a, m) {
a <- a %% m
for (x in 1:m) {
if ((a * x) %% m == 1) {
return(x)
}
}
return(1)
}
parsedEncryption <- gsub(" ", "", encryption) # removed whitespace
splitList <- strsplit(parsedEncryption, "")[[1]] # list of letters
y <- (match(splitList, letters) - 1) # index of letters
# D(y) = a^-1(y - b) mod m
return(paste(letters[((mmi(a, m) * (y - b)) %% m) + 1], collapse = ""))
}