Skip to content

Instantly share code, notes, and snippets.

@bquast
Created July 18, 2019 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bquast/1aec711fd082fc04a6a22b7c8ad5ef3a to your computer and use it in GitHub Desktop.
Save bquast/1aec711fd082fc04a6a22b7c8ad5ef3a to your computer and use it in GitHub Desktop.
Basic example of the RSA algorithm in R
# RSA example
#
# Bastiaan Quast
# International Telecommunication Union
# bastiaan.quast@itu.int
# Two people - Alice and Bob - want to communicate privately
# A third person Eve wants to read the private communication
Alice = list()
Bob = list()
# Bob generates a message 'hi'
# we can represent this numberically as 89 (h is the 8th letter of the alphabet, i the 9th)
Bob$m = 89
# Alice generates two random prime numbers
Alice$p = 53
Alice$q = 59
Alice$n = Alice$p * Alice$q
# calculate Phi(n)
Alice$Phi_n = (Alice$p-1)*(Alice$q-1)
# Alice choses an exponent
Alice$e = 3
# Alice calculates the private part of the key
Alice$d = (2*Alice$Phi_n + 1) / 3
# publish the public key (here by putting the global environment)
n = Alice$n
e = Alice$e
# Bob encrypts his message
c = Bob$m^e %% n
# install and load the GNU Multiple Percision Arithmetic R package
install.packages('gmp')
library(gmp)
# Alice decrypts Bob's message
Alice$cpowd <- as.bigz(c)^Alice$d
Alice$m = Alice$cpowd %% n
print(Alice$m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment