needs to be taken mod n for some reason.

This commit is contained in:
jude 2023-02-12 16:51:28 +00:00
parent 9f6584ba1a
commit d397cf352a

View File

@ -8,35 +8,39 @@ class PubKey {
encrypt(m) { encrypt(m) {
// Compute g^m r^n mod n^2 // Compute g^m r^n mod n^2
let r = this.n; let r = random2048();
while (r >= n) { while (r >= this.n) {
r = random2048(); r = random2048();
} }
// Compute g^m by binomial theorem. // Compute g^m by binomial theorem.
let gm = 1n + this.n * m; let gm = (1n + this.n * m) % this.n ** 2n;
// Compute g^m r^n from fact that g^n = 1 // Compute g^m r^n from crt
return fastModularExponentiation(gm * r, this.n, this.n ** 2); return (gm * fastModularExponentiation(r, this.n, this.n ** 2n)) % this.n ** 2n;
} }
} }
class PrivKey { class PrivKey {
constructor(lambda, mu) { constructor(p, q) {
this.lambda = lambda; this.n = p * q;
this.mu = mu; this.lambda = (p - 1n) * (q - 1n);
this.mu = fastModularExponentiation(this.lambda, this.lambda - 1n, this.n);
}
decrypt(c) {
return (
(((fastModularExponentiation(c, this.lambda, this.n ** 2n) - 1n) / this.n) *
(this.mu % this.n)) %
this.n
);
} }
} }
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
return;
p = generate_prime(); p = generate_prime();
q = generate_prime(); q = generate_prime();
let n = p * q;
let lambda = (p - 1n) * (q - 1n);
pubKey = new PubKey(p, q); pubKey = new PubKey(p, q);
privKey = new PrivKey(lambda, fastModularExponentiation(lambda, lambda - 1n, n)); privKey = new PrivKey(p, q);
}); });