In order to break RSA cryptography one needs to be able to factorise a large integer \(n\), which is known to be the product of two prime numbers \(n=p q\).
Given an integer \(n\), the factoring algorithm determines \(p, q\) such that \(n=pq\). We assume \(p,q\neq 1\).
Euclid described a classical algorithm for finding the greatest common divisor (gcd) of two positive integers \(m > n\). It may be implemented recursively as follows:
Another ingredient is the order finding algorithm, which we are also going to solve classically here, actually with the most naive algorithm
Shor’s algorithms can be implemented as follows
factoring <- function(n) {
for(i in c(1:20)){
## generate random number
m <- sample.int(n=n, size=1)
cat("m=", m, "\n")
## Check, whether m, n are co-prime
g <- gcd(n,m)
if(g != 1 ) return(g)
else {
## find the order of m modulo n
r <- findOrder(x=m, n=n)
cat("r=", r, "\n")
if(!is.na(r)) {
if((r %% 2) == 0) {
l <- gcd(m^(r/2)-1, n)
if(l > 1 && l < n) return(l)
}
}
}
}
cat("could not find a factor!\n")
return(NA)
}
And we can test whether it works
m= 25
[1] 5
m= 86
r= 12
[1] 7
m= 504
[1] 7
Note that this computation is a bit tricky in R
because of the integer arithmetic with large integers. However, for our example here, the code is sufficient.