@stellot/crypto
Version:
Crypto libraries for front and backend
68 lines (67 loc) • 2.67 kB
JavaScript
import asn from 'asn1.js';
import DecryptionElGamal from './decryption';
import EncryptionElGamal from './encryption';
import { BigInteger as BigInt } from 'jsbn';
import EncryptedValue from './encryptedValue';
import DecryptedValue from './decryptedValue';
import * as Utils from './utils';
export { ElGamal, EncryptionElGamal, DecryptionElGamal, DecryptedValue, EncryptedValue };
export function createEncryptionKeypair(primeBits = 2048) {
const { p, g, y, x } = ElGamal.generate(primeBits);
const privateKey = encodePrivateKey(p, g, y, x);
const publicKey = encodePublicKey(p, g, y);
return { privateKey, publicKey };
}
const ElGamalPublicKey = asn.define('DHPublicKeyForElGamalEncryption', function () {
this.seq().obj(this.key('p').int(), this.key('g').int(), this.key('y').int());
});
export function encodePublicKey(prime, generator, publicKey) {
return ElGamalPublicKey.encode({
p: new Buffer(prime.toByteArray()),
g: new Buffer(generator.toByteArray()),
y: new Buffer(publicKey.toByteArray()),
}, 'der');
}
export function decodePublicKey(der) {
return ElGamalPublicKey.decode(der, 'der');
}
const ElGamalPrivateKey = asn.define('DHPrivateKeyForElGamalEncryption', function () {
this.seq().obj(this.key('p').int(), this.key('g').int(), this.key('y').int(), this.key('x').int());
});
export function encodePrivateKey(prime, generator, y, x) {
return ElGamalPrivateKey.encode({
p: new Buffer(prime.toByteArray()),
g: new Buffer(generator.toByteArray()),
y: new Buffer(y.toByteArray()),
x: new Buffer(x.toByteArray()),
}, 'der');
}
export function decodePrivateKey(der) {
return ElGamalPrivateKey.decode(der, 'der');
}
export default class ElGamal {
static generate(primeBits = 2048) {
let q;
let p;
do {
q = Utils.getBigPrime(primeBits - 1);
p = q.shiftLeft(1).add(BigInt.ONE);
} while (!p.isProbablePrime());
let g;
do {
g = Utils.getRandomBigInt(new BigInt('3'), p);
} while (g.modPowInt(2, p).equals(BigInt.ONE) ||
g.modPow(q, p).equals(BigInt.ONE) ||
p.subtract(BigInt.ONE).remainder(g).equals(BigInt.ZERO) ||
p.subtract(BigInt.ONE).remainder(g.modInverse(p)).equals(BigInt.ZERO));
const x = Utils.getRandomBigInt(Utils.BIG_TWO, p.subtract(BigInt.ONE));
const y = g.modPow(x, p);
return { p, g, y, x };
}
static fromPrivateKey(p, g, y, x) {
return new DecryptionElGamal(p, g, y, x);
}
static fromPublicKey(p, g, y) {
return new EncryptionElGamal(p, g, y);
}
}