Mid refactor to stop polluting the namespace so much
This commit is contained in:
2
static/js/modules/crypto/main.js
Normal file
2
static/js/modules/crypto/main.js
Normal file
@ -0,0 +1,2 @@
|
||||
import { generate_keypair } from "./paillier.js";
|
||||
export { generate_keypair };
|
14
static/js/modules/crypto/math.js
Normal file
14
static/js/modules/crypto/math.js
Normal file
@ -0,0 +1,14 @@
|
||||
export function mod_exp(a, b, n) {
|
||||
let res = 1n;
|
||||
|
||||
while (b > 0n) {
|
||||
if (b % 2n === 1n) {
|
||||
res = (res * a) % n;
|
||||
}
|
||||
|
||||
b >>= 1n;
|
||||
a = (a * a) % n;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
61
static/js/modules/crypto/paillier.js
Normal file
61
static/js/modules/crypto/paillier.js
Normal file
@ -0,0 +1,61 @@
|
||||
import { random2048, generate_prime } from "./random_primes.js";
|
||||
import { mod_exp } from "./math.js";
|
||||
|
||||
let p, q, pubKey, privKey;
|
||||
|
||||
class PubKey {
|
||||
constructor(p, q) {
|
||||
this.n = p * q;
|
||||
// this.g = this.n + 1n;
|
||||
}
|
||||
|
||||
encrypt(m) {
|
||||
// Compute g^m r^n mod n^2
|
||||
let r = random2048();
|
||||
|
||||
// Resample to avoid modulo bias.
|
||||
while (r >= this.n) {
|
||||
r = random2048();
|
||||
}
|
||||
|
||||
// Compute g^m by binomial theorem.
|
||||
let gm = (1n + this.n * m) % this.n ** 2n;
|
||||
// Compute g^m r^n from crt
|
||||
return (gm * mod_exp(r, this.n, this.n ** 2n)) % this.n ** 2n;
|
||||
}
|
||||
}
|
||||
|
||||
class PrivKey {
|
||||
constructor(p, q) {
|
||||
this.n = p * q;
|
||||
this.lambda = (p - 1n) * (q - 1n);
|
||||
this.mu = mod_exp(this.lambda, this.lambda - 1n, this.n);
|
||||
}
|
||||
|
||||
decrypt(c) {
|
||||
return (
|
||||
(((mod_exp(c, this.lambda, this.n ** 2n) - 1n) / this.n) * this.mu) % this.n
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function generate_keypair() {
|
||||
if (window.sessionStorage.getItem("p") === null) {
|
||||
p = generate_prime();
|
||||
window.sessionStorage.setItem("p", p);
|
||||
} else {
|
||||
p = BigInt(window.sessionStorage.getItem("p"));
|
||||
}
|
||||
|
||||
if (window.sessionStorage.getItem("q") === null) {
|
||||
q = generate_prime();
|
||||
window.sessionStorage.setItem("q", q);
|
||||
} else {
|
||||
q = BigInt(window.sessionStorage.getItem("q"));
|
||||
}
|
||||
|
||||
pubKey = new PubKey(p, q);
|
||||
privKey = new PrivKey(p, q);
|
||||
|
||||
return { pubKey, privKey };
|
||||
}
|
1321
static/js/modules/crypto/random_primes.js
Normal file
1321
static/js/modules/crypto/random_primes.js
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user