RSA keygen. some other stuff
This commit is contained in:
@ -1,2 +1,4 @@
|
||||
import { generate_keypair } from "./paillier.js";
|
||||
export { generate_keypair };
|
||||
import { generate_rsa_keypair } from "./rsa.js";
|
||||
|
||||
export { generate_keypair, generate_rsa_keypair };
|
||||
|
@ -12,3 +12,24 @@ export function mod_exp(a, b, n) {
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
export function mod_inv(a, n) {
|
||||
let t = 0n;
|
||||
let new_t = 1n;
|
||||
let r = n;
|
||||
let new_r = a;
|
||||
|
||||
while (new_r !== 0n) {
|
||||
let quotient = r / new_r;
|
||||
t = new_t;
|
||||
new_t = t - quotient * new_t;
|
||||
r = new_r;
|
||||
new_r = r - quotient * new_r;
|
||||
}
|
||||
|
||||
if (t < 0) {
|
||||
t = t + n;
|
||||
}
|
||||
|
||||
return t;
|
||||
}
|
||||
|
47
static/js/modules/crypto/rsa.js
Normal file
47
static/js/modules/crypto/rsa.js
Normal file
@ -0,0 +1,47 @@
|
||||
import { generate_prime } from "./random_primes.js";
|
||||
import { mod_exp, mod_inv } from "./math.js";
|
||||
|
||||
let p, q, pubKey, privKey;
|
||||
|
||||
class PubKey {
|
||||
constructor(p, q) {
|
||||
this.n = p * q;
|
||||
this.e = 65537;
|
||||
}
|
||||
|
||||
decrypt(m) {
|
||||
return mod_exp(m, this.e, this.n);
|
||||
}
|
||||
}
|
||||
|
||||
class PrivKey {
|
||||
constructor(p, q) {
|
||||
this.n = p * q;
|
||||
this.d = mod_inv(65537, (q - 1) * (p - 1));
|
||||
}
|
||||
|
||||
encrypt(c) {
|
||||
return mod_exp(c, this.d, this.n);
|
||||
}
|
||||
}
|
||||
|
||||
export function generate_rsa_keypair() {
|
||||
if (window.sessionStorage.getItem("rsa_p") === null) {
|
||||
p = generate_prime();
|
||||
window.sessionStorage.setItem("rsa_p", p);
|
||||
} else {
|
||||
p = BigInt(window.sessionStorage.getItem("rsa_p"));
|
||||
}
|
||||
|
||||
if (window.sessionStorage.getItem("rsa_q") === null) {
|
||||
q = generate_prime();
|
||||
window.sessionStorage.setItem("rsa_q", q);
|
||||
} else {
|
||||
q = BigInt(window.sessionStorage.getItem("rsa_q"));
|
||||
}
|
||||
|
||||
pubKey = new PubKey(p, q);
|
||||
privKey = new PrivKey(p, q);
|
||||
|
||||
return { pubKey, privKey };
|
||||
}
|
Reference in New Issue
Block a user