Build a toy RSA key pair from two primes and a public exponent, then encrypt and decrypt a list of messages to prove the keys work.
What to build
Check the inputs, make the keys and run every message through encryption and decryption.
Requirements
- Line 1 is p q e. If p or q is not prime, print
p and q must be prime. If p equals q, printp and q must be different. If e is not between 2 and φ(n) − 1, or shares a factor with φ(n), printe does not work. Check in that order and stop at the first problem. - Otherwise print
n N phi F d D, where n = pq, φ = (p − 1)(q − 1) and d is the inverse of e modulo φ. - For each following message m, print
m -> c -> m2, with c = m^e mod n and m2 = c^d mod n. If m is not less than n, printm too biginstead.
Input
Line 1: p q e. Each following line: a message, a whole number.
Output
As described.
Constraints
p and q are at most 10⁶. 0 to 20 messages, each 0 to 10¹⁵. Use BigInt for the powers.
Example
Input:
61 53 17
65
123
Output:
n 3233 phi 3120 d 2753
65 -> 2790 -> 65
123 -> 855 -> 123
Why it works
Because e × d = 1 (mod φ(n)), raising to e and then to d gives m back for every m below n (Euler's theorem), which the round trip checks message by message.
Examples
61 53 17 65 123
n 3233 phi 3120 d 2753 65 -> 2790 -> 65 123 -> 855 -> 123
61 53 15 65
e does not work
Hints
Hint 1
A prime check up to the square root is fast enough for numbers up to 10⁶.
Hint 2
Reuse your fast modular power and modular inverse.
Solution
Show one correct solution (try it yourself first)
const isPrime = (n) => {
if (n < 2n) return false;
for (let d = 2n; d * d <= n; d++) if (n % d === 0n) return false;
return true;
};
const gcd = (a, b) => (b === 0n ? a : gcd(b, a % b));
function modPow(b, e, m) {
let result = 1n % m;
b %= m;
while (e > 0n) {
if (e & 1n) result = (result * b) % m;
b = (b * b) % m;
e >>= 1n;
}
return result;
}
function inverse(e, m) {
let [r0, r1] = [e, m];
let [s0, s1] = [1n, 0n];
while (r1 !== 0n) {
const q = r0 / r1;
[r0, r1] = [r1, r0 - q * r1];
[s0, s1] = [s1, s0 - q * s1];
}
return ((s0 % m) + m) % m;
}
const [p, q, e] = prompt().trim().split(/\s+/).map(BigInt);
if (!isPrime(p) || !isPrime(q)) console.log("p and q must be prime");
else if (p === q) console.log("p and q must be different");
else {
const n = p * q;
const phi = (p - 1n) * (q - 1n);
if (e < 2n || e >= phi || gcd(e, phi) !== 1n) console.log("e does not work");
else {
const d = inverse(e, phi);
console.log(`n ${n} phi ${phi} d ${d}`);
let line = prompt();
while (line !== null) {
if (line.trim() !== "") {
const m = BigInt(line.trim());
if (m >= n) console.log(`${m} too big`);
else {
const c = modPow(m, e, n);
console.log(`${m} -> ${c} -> ${modPow(c, d, n)}`);
}
}
line = prompt();
}
}
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step