-
Notifications
You must be signed in to change notification settings - Fork 0
/
RSA_algorithm.sf
64 lines (47 loc) · 954 Bytes
/
RSA_algorithm.sf
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
58
59
60
61
62
63
64
#!/usr/bin/ruby
# Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 12 January 2016
# https://github.com/trizen
# A simple example for the RSA algorithm.
require('ntheory')
var p = %S<ntheory>.random_strong_prime(2048)
var q = %S<ntheory>.random_strong_prime(2048)
var n = p*q
var phi = (p-1)*(q-1)
func gcd(u,v) {
while (v) {
(u, v) = (v, u % v)
}
return abs(u)
}
var e = 0
for (var k = 16 ; gcd(e, phi) != 1 ; ++k) {
e = (2**k + 1)
}
func invmod (a, n) {
var (u, w) = (1, 0)
var (q, r) = (0, 0)
var c = n
while (c != 0) {
(q, r) = divmod(a, c)
(a, c) = (c, r)
(u, w) = (w, u - q*w)
}
u += n if (u < 0)
return u
}
var d = invmod(e, phi)
func expmod(a,b,n) {
var c = 1
do {
(c *= a) %= n if b.is_odd
(a *= a) %= n
} while (b >>= 1)
return c
}
var m = 123456789
var c = expmod(m, e, n)
var M = expmod(c, d, n)
say M
assert_eq(M, m)