-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcryptography.js
More file actions
101 lines (92 loc) · 2.4 KB
/
Copy pathcryptography.js
File metadata and controls
101 lines (92 loc) · 2.4 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
function verifyPrimality(a) {
if (a % 2 == 0) {
if (a == 2) {
return true
}
}
else {
let div = 3
while (div * div <= a) {
if (a % div == 0) {
return false
}
else {
div += 2
}
}
if (div * div > a) {
return true
}
}
}
function greatestCommonDivisor(a, b) {
while (b != 0) {
let mod = a % b
a = b
b = mod
}
return a
}
function leastCommonMultiple(a, b) {
return(a * b / greatestCommonDivisor(a, b))
}
function lambda(a, b) {
return leastCommonMultiple(a - 1, b - 1)
}
function extendedEuclidean(lambdaN, e) {
var auxA = lambdaN, auxB = lambdaN
var auxC = e, auxD = 1
var c2 = 0, d2 = 0
while (auxC != 1) {
c2 = (auxA - Math.floor((auxA / auxC)) * auxC) % lambdaN
d2 = (auxB - Math.floor((auxA / auxC)) * auxD) % lambdaN
if (c2 < 0) {
c2 += lambdaN
}
else if (d2 < 0) {
d2 += lambdaN
}
auxA = auxC
auxB = auxD
auxC = c2
auxD = d2
if (auxC == 0 || auxD == 0) {
return console.error("Cannot calculate the private key with these numbers")
}
}
return auxD;
}
function handleRSA(p, q, e) {
if (p > 1 && q > 1) {
if (verifyPrimality(p) === true && verifyPrimality(q) === true) {
if (greatestCommonDivisor(e, lambda(p, q)) == 1) {
if (extendedEuclidean((p - 1) * (q - 1), e)) {
return console.log("The private key 'd' is: ", extendedEuclidean((p - 1) * (q - 1), e))
}
}
else{
return console.error("The public key is not a co-prime of the lambda function")
}
}
else {
return console.error("P or Q is not prime")
}
}
else {
return console.error("P or Q is invalid. Enter natural numbers greater than 1")
}
}
rl.question("Enter a prime number 'p': ", p => {
rl.question("Enter a prime number 'q': ", q => {
rl.question("Enter a public key 'e': ", e => {
rl.write('\n')
handleRSA(p, q, e)
rl.close()
})
})
})