UNPKG

snarkyjs-elgamal

Version:

This repository implements Elgmal, a partial homomorphic encryption scheme originally described by [Taher Elgamal in 1985](https://caislab.kaist.ac.kr/lecture/2010/spring/cs548/basic/B02.pdf). This implementation includes the original version of Elgamal,

72 lines 1.89 kB
import { Group, Scalar, Field, isReady, Struct, Experimental, } from 'snarkyjs'; import { modExp } from './lib.js'; export { ElGamalECC, ElGamalFF, Cipher }; await isReady; /** * ElGamal over an elliptic curve. */ class ElGamalECC { static encrypt(msg, y) { let k = Experimental.memoizeWitness(Scalar, Scalar.random); return { c: this.G.scale(k), d: y.toGroup().scale(k).add(msg), }; } static decrypt({ c, d }, priv) { let x = priv.s; let c_ = c.scale(x); let pm = d.sub(c_); return pm; } } ElGamalECC.G = Group.generator; class Cipher extends Struct({ c1: Field, c2: Field, }) { mul(c2) { return new Cipher({ c1: this.c1.mul(c2.c1), c2: this.c2.mul(c2.c2) }); } } /** * ElGamal over a finite field. */ class ElGamalFF { /** * Generate a key pair used for encrypting and decrypting. */ static generateKeys() { let x = Experimental.memoizeWitness(Field, Field.random); let h = modExp(this.G, x); return { pk: h, sk: x, }; } /** * Encrypts a Field element, with a public key `h`. * @param m Message * @param h Public key */ static encrypt(m, h) { let y = Experimental.memoizeWitness(Field, Field.random); let s = modExp(h, y); let c1 = modExp(this.G, y); let c2 = m.mul(s); return new Cipher({ c1, c2 }); } /** * Decrypts a cipher text, with a private key `x`. * @param m Message * @param h Public key */ static decrypt({ c1, c2 }, x) { let s = modExp(c1, x); let s_ = s.inv(); let m = c2.mul(s_); return m; } } ElGamalFF.G = Field('12418654782883325593414442427049395787963493412651469444558597405572177144507'); //# sourceMappingURL=elgamal.js.map