Riskless/static/js/modules/crypto/paillier.js

107 lines
2.3 KiB
JavaScript
Raw Normal View History

import { random2048, generate_prime } from "./random_primes.js";
import { mod_exp } from "./math.js";
2023-03-17 10:42:11 +00:00
class Cyphertext {
constructor(key, plainText) {
2023-02-11 14:59:24 +00:00
// Compute g^m r^n mod n^2
let r = random2048();
2023-02-11 14:59:24 +00:00
// Resample to avoid modulo bias.
2023-03-17 10:42:11 +00:00
while (r >= key.n) {
2023-02-11 14:59:24 +00:00
r = random2048();
}
// Compute g^m by binomial theorem.
2023-03-17 10:42:11 +00:00
let gm = (1n + key.n * plainText) % key.n ** 2n;
// Compute g^m r^n from crt
2023-03-17 10:42:11 +00:00
this.cyphertext = (gm * mod_exp(r, key.n, key.n ** 2n)) % key.n ** 2n;
this.r = r;
this.key = key;
this.plainText = plainText;
this.readOnly = false;
}
update(c) {
this.cyphertext *= c.cyphertext;
this.r *= c.r;
this.plainText += c.plainText;
}
toString() {
return "0x" + this.cyphertext.toString(16);
}
}
export class ReadOnlyCyphertext {
constructor(key, cyphertext) {
this.cyphertext = cyphertext;
this.key = key;
this.readOnly = true;
}
update(c) {
this.cyphertext *= c.cyphertext;
}
}
export class PaillierPubKey {
constructor(n) {
this.n = n;
this.g = this.n + 1n;
}
encrypt(m) {
return new Cyphertext(this, m);
2023-02-08 17:55:45 +00:00
}
2023-03-13 14:52:14 +00:00
toJSON() {
return {
n: "0x" + this.n.toString(16),
};
}
static fromJSON(data) {
return new PaillierPubKey(BigInt(data.n));
}
2023-02-08 17:55:45 +00:00
}
2023-03-13 14:52:14 +00:00
class PaillierPrivKey {
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
);
2023-02-08 15:52:02 +00:00
}
2023-02-08 17:55:45 +00:00
}
export function generate_keypair() {
2023-03-13 14:52:14 +00:00
let p, q, pubKey, privKey;
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"));
}
2023-02-08 17:55:45 +00:00
2023-03-13 14:52:14 +00:00
pubKey = new PaillierPubKey(p * q);
privKey = new PaillierPrivKey(p, q);
return { pubKey, privKey };
}