Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

paillier-bigint

Package Overview
Dependencies
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

paillier-bigint - npm Package Compare versions

Comparing version 3.0.2 to 3.0.3

lib/index.browser.bundle.iife.js

2

lib/index.browser.bundle.mod.js

@@ -1,1 +0,1 @@

const _ZERO=BigInt(0);const _ONE=BigInt(1);const _TWO=BigInt(2);function abs(a){a=BigInt(a);return a>=_ZERO?a:-a}function bitLength(a){a=BigInt(a);if(a===_ONE)return 1;let bits=1;do{bits++}while((a>>=_ONE)>_ONE);return bits}function eGcd(a,b){a=BigInt(a);b=BigInt(b);if(a<=_ZERO|b<=_ZERO)return NaN;let x=_ZERO;let y=_ONE;let u=_ONE;let v=_ZERO;while(a!==_ZERO){let q=b/a;let r=b%a;let m=x-u*q;let n=y-v*q;b=a;a=r;x=u;y=v;u=m;v=n}return{b:b,x:x,y:y}}function gcd(a,b){a=abs(a);b=abs(b);if(a===_ZERO)return b;else if(b===_ZERO)return a;let shift=_ZERO;while(!((a|b)&_ONE)){a>>=_ONE;b>>=_ONE;shift++}while(!(a&_ONE))a>>=_ONE;do{while(!(b&_ONE))b>>=_ONE;if(a>b){let x=a;a=b;b=x}b-=a}while(b);return a<<shift}async function isProbablyPrime(w,iterations=16){if(typeof w==="number"){w=BigInt(w)}{return new Promise((resolve,reject)=>{const worker=new Worker(_isProbablyPrimeWorkerUrl());worker.onmessage=event=>{worker.terminate();resolve(event.data.isPrime)};worker.onmessageerror=event=>{reject(event)};worker.postMessage({rnd:w,iterations:iterations,id:0})})}}function lcm(a,b){a=BigInt(a);b=BigInt(b);if(a===_ZERO&&b===_ZERO)return _ZERO;return abs(a*b)/gcd(a,b)}function modInv(a,n){if(a==_ZERO|n<=_ZERO)return NaN;let egcd=eGcd(toZn(a,n),n);if(egcd.b!==_ONE){return NaN}else{return toZn(egcd.x,n)}}function modPow(b,e,n){n=BigInt(n);if(n===_ZERO)return NaN;else if(n===_ONE)return _ZERO;b=toZn(b,n);e=BigInt(e);if(e<_ZERO){return modInv(modPow(b,abs(e),n),n)}let r=_ONE;while(e>0){if(e%_TWO===_ONE){r=r*b%n}e=e/_TWO;b=b**_TWO%n}return r}function prime(bitLength,iterations=16){if(bitLength<1)throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);return new Promise(resolve=>{let workerList=[];const _onmessage=(msg,newWorker)=>{if(msg.isPrime){for(let j=0;j<workerList.length;j++){workerList[j].terminate()}while(workerList.length){workerList.pop()}resolve(msg.value)}else{let buf=randBits(bitLength,true);let rnd=fromBuffer(buf);try{newWorker.postMessage({rnd:rnd,iterations:iterations,id:msg.id})}catch(error){}}};{let workerURL=_isProbablyPrimeWorkerUrl();for(let i=0;i<self.navigator.hardwareConcurrency;i++){let newWorker=new Worker(workerURL);newWorker.onmessage=event=>_onmessage(event.data,newWorker);workerList.push(newWorker)}}for(let i=0;i<workerList.length;i++){let buf=randBits(bitLength,true);let rnd=fromBuffer(buf);workerList[i].postMessage({rnd:rnd,iterations:iterations,id:i})}})}function primeSync(bitLength,iterations=16){if(bitLength<1)throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);let rnd=_ZERO;do{rnd=fromBuffer(randBytesSync(bitLength/8,true))}while(!_isProbablyPrime(rnd,iterations));return rnd}function randBetween(max,min=_ONE){if(max<=min)throw new Error("max must be > min");const interval=max-min;let bitLen=bitLength(interval);let rnd;do{let buf=randBits(bitLen);rnd=fromBuffer(buf)}while(rnd>interval);return rnd+min}function randBits(bitLength,forceLength=false){if(bitLength<1)throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);const byteLength=Math.ceil(bitLength/8);const rndBytes=randBytesSync(byteLength,false);const bitLengthMod8=bitLength%8;if(bitLengthMod8){rndBytes[0]=rndBytes[0]&2**bitLengthMod8-1}if(forceLength){const mask=bitLengthMod8?2**(bitLengthMod8-1):128;rndBytes[0]=rndBytes[0]|mask}return rndBytes}function randBytesSync(byteLength,forceLength=false){if(byteLength<1)throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`);let buf;{buf=new Uint8Array(byteLength);self.crypto.getRandomValues(buf)}if(forceLength)buf[0]=buf[0]|128;return buf}function toZn(a,n){n=BigInt(n);if(n<=0)return NaN;a=BigInt(a)%n;return a<0?a+n:a}function fromBuffer(buf){let ret=_ZERO;for(let i of buf.values()){let bi=BigInt(i);ret=(ret<<BigInt(8))+bi}return ret}function _isProbablyPrimeWorkerUrl(){let workerCode=`'use strict';const _ZERO = BigInt(0);const _ONE = BigInt(1);const _TWO = BigInt(2);const eGcd = ${eGcd.toString()};const modInv = ${modInv.toString()};const modPow = ${modPow.toString()};const toZn = ${toZn.toString()};const randBits = ${randBits.toString()};const randBytesSync = ${randBytesSync.toString()};const randBetween = ${randBetween.toString()};const isProbablyPrime = ${_isProbablyPrime.toString()};${bitLength.toString()}${fromBuffer.toString()}`;const onmessage=async function(event){const isPrime=await isProbablyPrime(event.data.rnd,event.data.iterations);postMessage({isPrime:isPrime,value:event.data.rnd,id:event.data.id})};workerCode+=`onmessage = ${onmessage.toString()};`;return _workerUrl(workerCode)}function _workerUrl(workerCode){workerCode=`(() => {${workerCode}})()`;const _blob=new Blob([workerCode],{type:"text/javascript"});return window.URL.createObjectURL(_blob)}function _isProbablyPrime(w,iterations=16){if(w===_TWO)return true;else if((w&_ONE)===_ZERO||w===_ONE)return false;const firstPrimes=[3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597];for(let i=0;i<firstPrimes.length&&BigInt(firstPrimes[i])<=w;i++){const p=BigInt(firstPrimes[i]);if(w===p)return true;else if(w%p===_ZERO)return false}let a=_ZERO,d=w-_ONE;while(d%_TWO===_ZERO){d/=_TWO;++a}let m=(w-_ONE)/_TWO**a;loop:do{let b=randBetween(w-_ONE,_TWO);let z=modPow(b,m,w);if(z===_ONE||z===w-_ONE)continue;for(let j=1;j<a;j++){z=modPow(z,_TWO,w);if(z===w-_ONE)continue loop;if(z===_ONE)break}return false}while(--iterations);return true}const _ONE$1=BigInt(1);const generateRandomKeys=async function(bitLength$1=3072,simpleVariant=false){let p,q,n,g,lambda,mu;do{p=await prime(Math.floor(bitLength$1/2)+1);q=await prime(Math.floor(bitLength$1/2));n=p*q}while(q===p||bitLength(n)!==bitLength$1);const phi=(p-_ONE$1)*(q-_ONE$1);const n2=n**BigInt(2);if(simpleVariant===true){g=n+_ONE$1;lambda=phi;mu=modInv(lambda,n)}else{g=getGenerator(n,n2);lambda=lcm(p-_ONE$1,q-_ONE$1);mu=modInv(L(modPow(g,lambda,n2),n),n)}const publicKey=new PublicKey(n,g);const privateKey=new PrivateKey(lambda,mu,publicKey,p,q);return{publicKey:publicKey,privateKey:privateKey}};const generateRandomKeysSync=function(bitLength$1=4096,simpleVariant=false){let p,q,n,g,lambda,mu;do{p=primeSync(Math.floor(bitLength$1/2)+1);q=primeSync(Math.floor(bitLength$1/2));n=p*q}while(q===p||bitLength(n)!==bitLength$1);const phi=(p-_ONE$1)*(q-_ONE$1);const n2=n**BigInt(2);if(simpleVariant===true){g=n+_ONE$1;lambda=phi;mu=modInv(lambda,n)}else{g=getGenerator(n,n2);lambda=lcm(p-_ONE$1,q-_ONE$1);mu=modInv(L(modPow(g,lambda,n2),n),n)}const publicKey=new PublicKey(n,g);const privateKey=new PrivateKey(lambda,mu,publicKey,p,q);return{publicKey:publicKey,privateKey:privateKey}};const PublicKey=class PublicKey{constructor(n,g){this.n=n;this._n2=this.n**BigInt(2);this.g=BigInt(g)}get bitLength(){return bitLength(this.n)}encrypt(m){const r=randBetween(this.n);return modPow(this.g,m,this._n2)*modPow(r,this.n,this._n2)%this._n2}addition(...ciphertexts){return ciphertexts.reduce((sum,next)=>sum*next%this._n2,_ONE$1)}multiply(c,k){return modPow(BigInt(c),BigInt(k),this._n2)}};const PrivateKey=class PrivateKey{constructor(lambda,mu,publicKey,p=null,q=null){this.lambda=lambda;this.mu=mu;this._p=p||null;this._q=q||null;this.publicKey=publicKey}get bitLength(){return bitLength(this.publicKey.n)}get n(){return this.publicKey.n}decrypt(c){return L(modPow(c,this.lambda,this.publicKey._n2),this.publicKey.n)*this.mu%this.publicKey.n}};function L(a,n){return(a-_ONE$1)/n}function getGenerator(n,n2=modPow(n,2)){const alpha=randBetween(n);const beta=randBetween(n);return(alpha*n+_ONE$1)*modPow(beta,n,n2)%n2}export{PrivateKey,PublicKey,generateRandomKeys,generateRandomKeysSync};
function n(n){return(n=BigInt(n))>=0n?n:-n}function t(n){if(1n===(n=BigInt(n)))return 1;let t=1;do{t++}while((n>>=1n)>1n);return t}function e(n,t){if((n=BigInt(n))<=0n|(t=BigInt(t))<=0n)return NaN;let e=0n,r=1n,i=1n,o=0n;for(;0n!==n;){const s=t/n,u=t%n,c=e-i*s,a=r-o*s;t=n,n=u,e=i,r=o,i=c,o=a}return{b:t,x:e,y:r}}function r(t,e){return t=BigInt(t),e=BigInt(e),0n===t&&0n===e?0n:n(t*e)/function(t,e){if(t=n(t),e=n(e),0n===t)return e;if(0n===e)return t;let r=0n;for(;!(1n&(t|e));)t>>=1n,e>>=1n,r++;for(;!(1n&t);)t>>=1n;do{for(;!(1n&e);)e>>=1n;if(t>e){const n=t;t=e,e=n}e-=t}while(e);return t<<r}(t,e)}function i(n,t){const r=e(s(n,t),t);return 1n!==r.b?NaN:s(r.x,t)}function o(t,e,r){if(0n===(r=BigInt(r)))return NaN;if(1n===r)return 0n;if(t=s(t,r),(e=BigInt(e))<0n)return i(o(t,n(e),r),r);let u=1n;for(;e>0;)e%2n===1n&&(u=u*t%r),e/=2n,t=t**2n%r;return u}function s(n,t){return(t=BigInt(t))<=0?NaN:(n=BigInt(n)%t)<0?n+t:n}function u(n,t=16){return"number"==typeof n&&(n=BigInt(n)),new Promise((e,r)=>{const i=new Worker(d());i.onmessage=n=>{i.terminate(),e(n.data.isPrime)},i.onmessageerror=n=>{r(n)},i.postMessage({rnd:n,iterations:t,id:0})})}function c(n,t=16){if(n<1)throw new RangeError(`bitLength MUST be > 0 and it is ${n}`);return new Promise(e=>{const r=[],i=(i,o)=>{if(i.isPrime){for(let n=0;n<r.length;n++)r[n].terminate();for(;r.length;)r.pop();e(i.value)}else{const e=h(l(n,!0));try{o.postMessage({rnd:e,iterations:t,id:i.id})}catch(n){}}};{const n=d();for(let t=0;t<self.navigator.hardwareConcurrency-1;t++){const t=new Worker(n);t.onmessage=n=>i(n.data,t),r.push(t)}}for(let e=0;e<r.length;e++){const i=h(l(n,!0));r[e].postMessage({rnd:i,iterations:t,id:e})}})}function a(n,t=16){if(n<1)throw new RangeError(`bitLength MUST be > 0 and it is ${n}`);let e=0n;do{e=h(l(n,!0))}while(!w(e,t));return e}function f(n,e=1n){if(n<=e)throw new Error("max must be > min");const r=n-e,i=t(r);let o;do{o=h(l(i))}while(o>r);return o+e}function l(n,t=!1){if(n<1)throw new RangeError(`bitLength MUST be > 0 and it is ${n}`);const e=g(Math.ceil(n/8),!1),r=n%8;if(r&&(e[0]=e[0]&2**r-1),t){const n=r?2**(r-1):128;e[0]=e[0]|n}return e}function g(n,t=!1){if(n<1)throw new RangeError(`byteLength MUST be > 0 and it is ${n}`);{const e=new Uint8Array(n);return self.crypto.getRandomValues(e),t&&(e[0]=128|e[0]),e}}function h(n){let t=0n;for(const e of n.values()){const n=BigInt(e);t=(t<<BigInt(8))+n}return t}function d(){let n=`'use strict';const ${e.name}=${e.toString()};const ${i.name}=${i.toString()};const ${o.name}=${o.toString()};const ${s.name}=${s.toString()};const ${l.name}=${l.toString()};const ${g.name}=${g.toString()};const ${f.name}=${f.toString()};const ${u.name}=${w.toString()};${t.toString()}${h.toString()}`;return n+=`onmessage = ${async function(n){const t=await u(n.data.rnd,n.data.iterations);postMessage({isPrime:t,value:n.data.rnd,id:n.data.id})}.toString()};`,function(n){n=`(() => {${n}})()`;const t=new Blob([n],{type:"text/javascript"});return window.URL.createObjectURL(t)}(n)}function w(n,t=16){if(2n===n)return!0;if(0n===(1n&n)||1n===n)return!1;const e=[3n,5n,7n,11n,13n,17n,19n,23n,29n,31n,37n,41n,43n,47n,53n,59n,61n,67n,71n,73n,79n,83n,89n,97n,101n,103n,107n,109n,113n,127n,131n,137n,139n,149n,151n,157n,163n,167n,173n,179n,181n,191n,193n,197n,199n,211n,223n,227n,229n,233n,239n,241n,251n,257n,263n,269n,271n,277n,281n,283n,293n,307n,311n,313n,317n,331n,337n,347n,349n,353n,359n,367n,373n,379n,383n,389n,397n,401n,409n,419n,421n,431n,433n,439n,443n,449n,457n,461n,463n,467n,479n,487n,491n,499n,503n,509n,521n,523n,541n,547n,557n,563n,569n,571n,577n,587n,593n,599n,601n,607n,613n,617n,619n,631n,641n,643n,647n,653n,659n,661n,673n,677n,683n,691n,701n,709n,719n,727n,733n,739n,743n,751n,757n,761n,769n,773n,787n,797n,809n,811n,821n,823n,827n,829n,839n,853n,857n,859n,863n,877n,881n,883n,887n,907n,911n,919n,929n,937n,941n,947n,953n,967n,971n,977n,983n,991n,997n,1009n,1013n,1019n,1021n,1031n,1033n,1039n,1049n,1051n,1061n,1063n,1069n,1087n,1091n,1093n,1097n,1103n,1109n,1117n,1123n,1129n,1151n,1153n,1163n,1171n,1181n,1187n,1193n,1201n,1213n,1217n,1223n,1229n,1231n,1237n,1249n,1259n,1277n,1279n,1283n,1289n,1291n,1297n,1301n,1303n,1307n,1319n,1321n,1327n,1361n,1367n,1373n,1381n,1399n,1409n,1423n,1427n,1429n,1433n,1439n,1447n,1451n,1453n,1459n,1471n,1481n,1483n,1487n,1489n,1493n,1499n,1511n,1523n,1531n,1543n,1549n,1553n,1559n,1567n,1571n,1579n,1583n,1597n];for(let t=0;t<e.length&&e[t]<=n;t++){const r=e[t];if(n===r)return!0;if(n%r===0n)return!1}let r=0n;const i=n-1n;let s=i;for(;s%2n===0n;)s/=2n,++r;const u=i/2n**r;do{let t=o(f(i,2n),u,n);if(1n===t||t===i)continue;let e=1;for(;e<r&&(t=o(t,2n,n),t!==i);){if(1n===t)return!1;e++}if(t!==i)return!1}while(--t);return!0}class m{constructor(n,t){this.n=n,this._n2=this.n**2n,this.g=t}get bitLength(){return t(this.n)}encrypt(n){const t=f(this.n);return o(this.g,n,this._n2)*o(t,this.n,this._n2)%this._n2}addition(...n){return n.reduce((n,t)=>n*t%this._n2,1n)}multiply(n,t){return o(BigInt(n),BigInt(t),this._n2)}}class b{constructor(n,t,e,r=null,i=null){this.lambda=n,this.mu=t,this._p=r||null,this._q=i||null,this.publicKey=e}get bitLength(){return t(this.publicKey.n)}get n(){return this.publicKey.n}decrypt(n){return p(o(n,this.lambda,this.publicKey._n2),this.publicKey.n)*this.mu%this.publicKey.n}}function p(n,t){return(n-1n)/t}async function $(n=3072,e=!1){let s,u,a,f,l,g;do{s=await c(Math.floor(n/2)+1),u=await c(Math.floor(n/2)),a=s*u}while(u===s||t(a)!==n);const h=a**2n;!0===e?(f=a+1n,l=(s-1n)*(u-1n),g=i(l,a)):(f=B(a,h),l=r(s-1n,u-1n),g=i(p(o(f,l,h),a),a));const d=new m(a,f);return{publicKey:d,privateKey:new b(l,g,d,s,u)}}function y(n=4096,e=!1){let s,u,c,f,l,g;do{s=a(Math.floor(n/2)+1),u=a(Math.floor(n/2)),c=s*u}while(u===s||t(c)!==n);const h=c**2n;!0===e?(f=c+1n,l=(s-1n)*(u-1n),g=i(l,c)):(f=B(c,h),l=r(s-1n,u-1n),g=i(p(o(f,l,h),c),c));const d=new m(c,f);return{publicKey:d,privateKey:new b(l,g,d,s,u)}}function B(n,t=o(n,2)){return(f(n)*n+1n)*o(f(n),n,t)%t}export{b as PrivateKey,m as PublicKey,$ as generateRandomKeys,y as generateRandomKeysSync};

@@ -1,6 +0,121 @@

import { bitLength, prime, modInv, modPow, lcm, primeSync, randBetween } from 'bigint-crypto-utils'
import { bitLength, randBetween, modPow, prime, modInv, lcm, primeSync } from 'bigint-crypto-utils'
const _ONE = BigInt(1)
/**
* Class for a Paillier public key
*/
class PublicKey {
/**
* Creates an instance of class PublicKey
* @param {bigint} n - the public modulo
* @param {bigint} g - the public generator
*/
constructor (n, g) {
this.n = n
this._n2 = this.n ** 2n // cache n^2
this.g = g
}
/**
* Get the bit length of the public modulo
* @returns {number} - bit length of the public modulo
*/
get bitLength () {
return bitLength(this.n)
}
/**
* Paillier public-key encryption
*
* @param {bigint} m - a bigint representation of a cleartext message
*
* @returns {bigint} - the encryption of m with this public key
*/
encrypt (m) {
const r = randBetween(this.n)
return (modPow(this.g, m, this._n2) * modPow(r, this.n, this._n2)) % this._n2
}
/**
* Homomorphic addition
*
* @param {...bigint} ciphertexts - n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key
*
* @returns {bigint} - the encryption of (m_1 + ... + m_2) with this public key
*/
addition (...ciphertexts) {
return ciphertexts.reduce((sum, next) => sum * next % (this._n2), 1n)
}
/**
* Pseudo-homomorphic Paillier multiplication
*
* @param {bigint} c - a number m encrypted with this public key
* @param {bigint | number} k - either a bigint or a number
*
* @returns {bigint} - the encryption of k·m with this public key
*/
multiply (c, k) {
return modPow(BigInt(c), BigInt(k), this._n2)
}
}
/**
* Class for Paillier private keys.
*/
class PrivateKey {
/**
* Creates an instance of class PrivateKey
*
* @param {bigint} lambda
* @param {bigint} mu
* @param {PublicKey} publicKey
* @param {bigint} [p = null] - a big prime
* @param {bigint} [q = null] - a big prime
*/
constructor (lambda, mu, publicKey, p = null, q = null) {
this.lambda = lambda
this.mu = mu
this._p = p || null
this._q = q || null
this.publicKey = publicKey
}
/**
* Get the bit length of the public modulo
* @returns {number} - bit length of the public modulo
*/
get bitLength () {
return bitLength(this.publicKey.n)
}
/**
* Get the public modulo n=p·q
* @returns {bigint} - the public modulo n=p·q
*/
get n () {
return this.publicKey.n
}
/**
* Paillier private-key decryption
*
* @param {bigint} c - a bigint encrypted with the public key
*
* @returns {bigint} - the decryption of c with this private key
*/
decrypt (c) {
return (L(modPow(c, this.lambda, this.publicKey._n2), this.publicKey.n) * this.mu) % this.publicKey.n
}
}
function L (a, n) {
return (a - 1n) / n
}
/**
* Paillier cryptosystem for both Node.js and native JS (browsers and webviews)
* @module paillier-bigint
*/
/**
* @typedef {Object} KeyPair

@@ -10,6 +125,7 @@ * @property {PublicKey} publicKey - a Paillier's public key

*/
/**
* Generates a pair private, public key for the Paillier cryptosystem.
*
* @param {number} [bitLength = 3072] - the bit length of the public modulo
* @param {number} [bitlength = 3072] - the bit length of the public modulo
* @param {boolean} [simplevariant = false] - use the simple variant to compute the generator (g=n+1)

@@ -19,14 +135,14 @@ *

*/
const generateRandomKeys = async function (bitLength$1 = 3072, simpleVariant = false) {
async function generateRandomKeys (bitlength = 3072, simpleVariant = false) {
let p, q, n, g, lambda, mu
// if p and q are bitLength/2 long -> 2**(bitLength - 2) <= n < 2**(bitLength)
do {
p = await prime(Math.floor(bitLength$1 / 2) + 1)
q = await prime(Math.floor(bitLength$1 / 2))
p = await prime(Math.floor(bitlength / 2) + 1)
q = await prime(Math.floor(bitlength / 2))
n = p * q
} while (q === p || bitLength(n) !== bitLength$1)
} while (q === p || bitLength(n) !== bitlength)
const phi = (p - _ONE) * (q - _ONE)
const phi = (p - 1n) * (q - 1n)
const n2 = n ** BigInt(2)
const n2 = n ** 2n

@@ -37,3 +153,3 @@ if (simpleVariant === true) {

// g=n+1, lambda=(p-1)(q-1), mu=lambda.invertm(n)
g = n + _ONE
g = n + 1n
lambda = phi

@@ -43,3 +159,3 @@ mu = modInv(lambda, n)

g = getGenerator(n, n2)
lambda = lcm(p - _ONE, q - _ONE)
lambda = lcm(p - 1n, q - 1n)
mu = modInv(L(modPow(g, lambda, n2), n), n)

@@ -57,3 +173,3 @@ }

*
* @param {number} [bitLength = 4096] - the bit length of the public modulo
* @param {number} [bitlength = 4096] - the bit length of the public modulo
* @param {boolean} [simplevariant = false] - use the simple variant to compute the generator (g=n+1)

@@ -63,14 +179,14 @@ *

*/
const generateRandomKeysSync = function (bitLength$1 = 4096, simpleVariant = false) {
function generateRandomKeysSync (bitlength = 4096, simpleVariant = false) {
let p, q, n, g, lambda, mu
// if p and q are bitLength/2 long -> 2**(bitLength - 2) <= n < 2**(bitLength)
do {
p = primeSync(Math.floor(bitLength$1 / 2) + 1)
q = primeSync(Math.floor(bitLength$1 / 2))
p = primeSync(Math.floor(bitlength / 2) + 1)
q = primeSync(Math.floor(bitlength / 2))
n = p * q
} while (q === p || bitLength(n) !== bitLength$1)
} while (q === p || bitLength(n) !== bitlength)
const phi = (p - _ONE) * (q - _ONE)
const phi = (p - 1n) * (q - 1n)
const n2 = n ** BigInt(2)
const n2 = n ** 2n

@@ -81,3 +197,3 @@ if (simpleVariant === true) {

// g=n+1, lambda=(p-1)(q-1), mu=lambda.invertm(n)
g = n + _ONE
g = n + 1n
lambda = phi

@@ -87,3 +203,3 @@ mu = modInv(lambda, n)

g = getGenerator(n, n2)
lambda = lcm(p - _ONE, q - _ONE)
lambda = lcm(p - 1n, q - 1n)
mu = modInv(L(modPow(g, lambda, n2), n), n)

@@ -97,120 +213,8 @@ }

/**
* Class for a Paillier public key
*/
const PublicKey = class PublicKey {
/**
* Creates an instance of class PublicKey
* @param {bigint} n - the public modulo
* @param {bigint | number} g - the public generator
*/
constructor (n, g) {
this.n = n
this._n2 = this.n ** BigInt(2) // cache n^2
this.g = BigInt(g)
}
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
get bitLength () {
return bitLength(this.n)
}
/**
* Paillier public-key encryption
*
* @param {bigint} m - a bigint representation of a cleartext message
*
* @returns {bigint} - the encryption of m with this public key
*/
encrypt (m) {
const r = randBetween(this.n)
return (modPow(this.g, m, this._n2) * modPow(r, this.n, this._n2)) % this._n2
}
/**
* Homomorphic addition
*
* @param {...bigint} ciphertexts - n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key
*
* @returns {bigint} - the encryption of (m_1 + ... + m_2) with this public key
*/
addition (...ciphertexts) {
return ciphertexts.reduce((sum, next) => sum * next % (this._n2), _ONE)
}
/**
* Pseudo-homomorphic Paillier multiplication
*
* @param {bigint} c - a number m encrypted with this public key
* @param {bigint | number} k - either a bigint or a number
*
* @returns {bigint} - the encryption of k·m with this public key
*/
multiply (c, k) {
return modPow(BigInt(c), BigInt(k), this._n2)
}
}
/**
* Class for Paillier private keys.
*/
const PrivateKey = class PrivateKey {
/**
* Creates an instance of class PrivateKey
*
* @param {bigint} lambda
* @param {bigint} mu
* @param {PublicKey} publicKey
* @param {bigint} [p = null] - a big prime
* @param {bigint} [q = null] - a big prime
*/
constructor (lambda, mu, publicKey, p = null, q = null) {
this.lambda = lambda
this.mu = mu
this._p = p || null
this._q = q || null
this.publicKey = publicKey
}
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
get bitLength () {
return bitLength(this.publicKey.n)
}
/**
* Get the public modulo n=p·q
* @returns {bigint} - the public modulo n=p·q
*/
get n () {
return this.publicKey.n
}
/**
* Paillier private-key decryption
*
* @param {bigint} c - a bigint encrypted with the public key
*
* @returns {bigint} - the decryption of c with this private key
*/
decrypt (c) {
return (L(modPow(c, this.lambda, this.publicKey._n2), this.publicKey.n) * this.mu) % this.publicKey.n
}
}
function L (a, n) {
return (a - _ONE) / n
}
function getGenerator (n, n2 = modPow(n, 2)) {
const alpha = randBetween(n)
const beta = randBetween(n)
return ((alpha * n + _ONE) * modPow(beta, n, n2)) % n2
return ((alpha * n + 1n) * modPow(beta, n, n2)) % n2
}
export { PrivateKey, PublicKey, generateRandomKeys, generateRandomKeysSync }

@@ -7,5 +7,120 @@ 'use strict'

const _ONE = BigInt(1)
/**
* Class for a Paillier public key
*/
class PublicKey {
/**
* Creates an instance of class PublicKey
* @param {bigint} n - the public modulo
* @param {bigint} g - the public generator
*/
constructor (n, g) {
this.n = n
this._n2 = this.n ** 2n // cache n^2
this.g = g
}
/**
* Get the bit length of the public modulo
* @returns {number} - bit length of the public modulo
*/
get bitLength () {
return bcu.bitLength(this.n)
}
/**
* Paillier public-key encryption
*
* @param {bigint} m - a bigint representation of a cleartext message
*
* @returns {bigint} - the encryption of m with this public key
*/
encrypt (m) {
const r = bcu.randBetween(this.n)
return (bcu.modPow(this.g, m, this._n2) * bcu.modPow(r, this.n, this._n2)) % this._n2
}
/**
* Homomorphic addition
*
* @param {...bigint} ciphertexts - n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key
*
* @returns {bigint} - the encryption of (m_1 + ... + m_2) with this public key
*/
addition (...ciphertexts) {
return ciphertexts.reduce((sum, next) => sum * next % (this._n2), 1n)
}
/**
* Pseudo-homomorphic Paillier multiplication
*
* @param {bigint} c - a number m encrypted with this public key
* @param {bigint | number} k - either a bigint or a number
*
* @returns {bigint} - the encryption of k·m with this public key
*/
multiply (c, k) {
return bcu.modPow(BigInt(c), BigInt(k), this._n2)
}
}
/**
* Class for Paillier private keys.
*/
class PrivateKey {
/**
* Creates an instance of class PrivateKey
*
* @param {bigint} lambda
* @param {bigint} mu
* @param {PublicKey} publicKey
* @param {bigint} [p = null] - a big prime
* @param {bigint} [q = null] - a big prime
*/
constructor (lambda, mu, publicKey, p = null, q = null) {
this.lambda = lambda
this.mu = mu
this._p = p || null
this._q = q || null
this.publicKey = publicKey
}
/**
* Get the bit length of the public modulo
* @returns {number} - bit length of the public modulo
*/
get bitLength () {
return bcu.bitLength(this.publicKey.n)
}
/**
* Get the public modulo n=p·q
* @returns {bigint} - the public modulo n=p·q
*/
get n () {
return this.publicKey.n
}
/**
* Paillier private-key decryption
*
* @param {bigint} c - a bigint encrypted with the public key
*
* @returns {bigint} - the decryption of c with this private key
*/
decrypt (c) {
return (L(bcu.modPow(c, this.lambda, this.publicKey._n2), this.publicKey.n) * this.mu) % this.publicKey.n
}
}
function L (a, n) {
return (a - 1n) / n
}
/**
* Paillier cryptosystem for both Node.js and native JS (browsers and webviews)
* @module paillier-bigint
*/
/**
* @typedef {Object} KeyPair

@@ -15,6 +130,7 @@ * @property {PublicKey} publicKey - a Paillier's public key

*/
/**
* Generates a pair private, public key for the Paillier cryptosystem.
*
* @param {number} [bitLength = 3072] - the bit length of the public modulo
* @param {number} [bitlength = 3072] - the bit length of the public modulo
* @param {boolean} [simplevariant = false] - use the simple variant to compute the generator (g=n+1)

@@ -24,14 +140,14 @@ *

*/
const generateRandomKeys = async function (bitLength = 3072, simpleVariant = false) {
async function generateRandomKeys (bitlength = 3072, simpleVariant = false) {
let p, q, n, g, lambda, mu
// if p and q are bitLength/2 long -> 2**(bitLength - 2) <= n < 2**(bitLength)
do {
p = await bcu.prime(Math.floor(bitLength / 2) + 1)
q = await bcu.prime(Math.floor(bitLength / 2))
p = await bcu.prime(Math.floor(bitlength / 2) + 1)
q = await bcu.prime(Math.floor(bitlength / 2))
n = p * q
} while (q === p || bcu.bitLength(n) !== bitLength)
} while (q === p || bcu.bitLength(n) !== bitlength)
const phi = (p - _ONE) * (q - _ONE)
const phi = (p - 1n) * (q - 1n)
const n2 = n ** BigInt(2)
const n2 = n ** 2n

@@ -42,3 +158,3 @@ if (simpleVariant === true) {

// g=n+1, lambda=(p-1)(q-1), mu=lambda.invertm(n)
g = n + _ONE
g = n + 1n
lambda = phi

@@ -48,3 +164,3 @@ mu = bcu.modInv(lambda, n)

g = getGenerator(n, n2)
lambda = bcu.lcm(p - _ONE, q - _ONE)
lambda = bcu.lcm(p - 1n, q - 1n)
mu = bcu.modInv(L(bcu.modPow(g, lambda, n2), n), n)

@@ -62,3 +178,3 @@ }

*
* @param {number} [bitLength = 4096] - the bit length of the public modulo
* @param {number} [bitlength = 4096] - the bit length of the public modulo
* @param {boolean} [simplevariant = false] - use the simple variant to compute the generator (g=n+1)

@@ -68,14 +184,14 @@ *

*/
const generateRandomKeysSync = function (bitLength = 4096, simpleVariant = false) {
function generateRandomKeysSync (bitlength = 4096, simpleVariant = false) {
let p, q, n, g, lambda, mu
// if p and q are bitLength/2 long -> 2**(bitLength - 2) <= n < 2**(bitLength)
do {
p = bcu.primeSync(Math.floor(bitLength / 2) + 1)
q = bcu.primeSync(Math.floor(bitLength / 2))
p = bcu.primeSync(Math.floor(bitlength / 2) + 1)
q = bcu.primeSync(Math.floor(bitlength / 2))
n = p * q
} while (q === p || bcu.bitLength(n) !== bitLength)
} while (q === p || bcu.bitLength(n) !== bitlength)
const phi = (p - _ONE) * (q - _ONE)
const phi = (p - 1n) * (q - 1n)
const n2 = n ** BigInt(2)
const n2 = n ** 2n

@@ -86,3 +202,3 @@ if (simpleVariant === true) {

// g=n+1, lambda=(p-1)(q-1), mu=lambda.invertm(n)
g = n + _ONE
g = n + 1n
lambda = phi

@@ -92,3 +208,3 @@ mu = bcu.modInv(lambda, n)

g = getGenerator(n, n2)
lambda = bcu.lcm(p - _ONE, q - _ONE)
lambda = bcu.lcm(p - 1n, q - 1n)
mu = bcu.modInv(L(bcu.modPow(g, lambda, n2), n), n)

@@ -102,118 +218,6 @@ }

/**
* Class for a Paillier public key
*/
const PublicKey = class PublicKey {
/**
* Creates an instance of class PublicKey
* @param {bigint} n - the public modulo
* @param {bigint | number} g - the public generator
*/
constructor (n, g) {
this.n = n
this._n2 = this.n ** BigInt(2) // cache n^2
this.g = BigInt(g)
}
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
get bitLength () {
return bcu.bitLength(this.n)
}
/**
* Paillier public-key encryption
*
* @param {bigint} m - a bigint representation of a cleartext message
*
* @returns {bigint} - the encryption of m with this public key
*/
encrypt (m) {
const r = bcu.randBetween(this.n)
return (bcu.modPow(this.g, m, this._n2) * bcu.modPow(r, this.n, this._n2)) % this._n2
}
/**
* Homomorphic addition
*
* @param {...bigint} ciphertexts - n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key
*
* @returns {bigint} - the encryption of (m_1 + ... + m_2) with this public key
*/
addition (...ciphertexts) {
return ciphertexts.reduce((sum, next) => sum * next % (this._n2), _ONE)
}
/**
* Pseudo-homomorphic Paillier multiplication
*
* @param {bigint} c - a number m encrypted with this public key
* @param {bigint | number} k - either a bigint or a number
*
* @returns {bigint} - the encryption of k·m with this public key
*/
multiply (c, k) {
return bcu.modPow(BigInt(c), BigInt(k), this._n2)
}
}
/**
* Class for Paillier private keys.
*/
const PrivateKey = class PrivateKey {
/**
* Creates an instance of class PrivateKey
*
* @param {bigint} lambda
* @param {bigint} mu
* @param {PublicKey} publicKey
* @param {bigint} [p = null] - a big prime
* @param {bigint} [q = null] - a big prime
*/
constructor (lambda, mu, publicKey, p = null, q = null) {
this.lambda = lambda
this.mu = mu
this._p = p || null
this._q = q || null
this.publicKey = publicKey
}
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
get bitLength () {
return bcu.bitLength(this.publicKey.n)
}
/**
* Get the public modulo n=p·q
* @returns {bigint} - the public modulo n=p·q
*/
get n () {
return this.publicKey.n
}
/**
* Paillier private-key decryption
*
* @param {bigint} c - a bigint encrypted with the public key
*
* @returns {bigint} - the decryption of c with this private key
*/
decrypt (c) {
return (L(bcu.modPow(c, this.lambda, this.publicKey._n2), this.publicKey.n) * this.mu) % this.publicKey.n
}
}
function L (a, n) {
return (a - _ONE) / n
}
function getGenerator (n, n2 = bcu.modPow(n, 2)) {
const alpha = bcu.randBetween(n)
const beta = bcu.randBetween(n)
return ((alpha * n + _ONE) * bcu.modPow(beta, n, n2)) % n2
return ((alpha * n + 1n) * bcu.modPow(beta, n, n2)) % n2
}

@@ -220,0 +224,0 @@

{
"name": "paillier-bigint",
"version": "3.0.2",
"version": "3.0.3",
"description": "An implementation of the Paillier cryptosystem using native JS (ECMA 2020) implementation of BigInt",

@@ -34,3 +34,3 @@ "keywords": [

"build:browserTests": "rollup -c build/rollup.tests.config.js",
"build:docs": "jsdoc2md --template=./src/doc/readme-template.md --files ./src/js/index.js > README.md",
"build:docs": "node build/build.docs.js",
"build:dts": "node build/build.dts.js",

@@ -49,3 +49,3 @@ "build": "run-s build:**",

"/test/browser/",
"/lib/index.browser.bundle.js",
"/lib/index.browser.bundle.iife.js",
"/lib/index.browser.bundle.mod.js"

@@ -63,3 +63,3 @@ ]

"npm-run-all": "^4.1.5",
"rollup": "^2.2.0",
"rollup": "^2.3.4",
"rollup-plugin-terser": "^5.3.0",

@@ -70,4 +70,4 @@ "standard": "^14.3.3",

"dependencies": {
"bigint-crypto-utils": "^2.5.2"
"bigint-crypto-utils": "^3.0.0"
}
}

@@ -72,2 +72,3 @@ [![JavaScript Style Guide](https://cdn.rawgit.com/standard/standard/master/badge.svg)](https://github.com/standard/standard)

`paillier-bigint` can be imported to your project with `npm`:
```bash

@@ -77,60 +78,81 @@ npm install paillier-bigint

NPM installation defaults to the ES6 module for browsers and the CJS one for Node.js.
NPM installation defaults to the ES6 module for native JS and the CJS one for Node.js.
For web browsers, you can also directly download the minimized version of the [IIFE file](https://aw.githubusercontent.com/juanelas/paillier-bigint/master/dist/index.browser.bundle.js) or the [ES6 module](https://raw.githubusercontent.com/juanelas/paillier-bigint/master/dist/index.browser.bundle.mod.js) from GitHub.
For web browsers, you can also directly download the minimized version of the [IIFE file](https://aw.githubusercontent.com/juanelas/paillier-bigint/master/dist/index.browser.bundle.iife.js) or the [ES6 bundle module](https://raw.githubusercontent.com/juanelas/paillier-bigint/master/dist/index.browser.bundle.mod.js) from GitHub.
## Usage
Import your module as :
- Node.js
```javascript
const paillierBigint = require('paillier-bigint')
... // your code here
```
- JavaScript native project or TypeScript
```javascript
import * as paillierBigint from 'paillier-bigint'
... // your code here
```
> BigInt is [ES-2020](https://tc39.es/ecma262/#sec-bigint-objects). In order to use it with TypeScript you should set `lib` (and probably also `target` and `module`) to `esnext` in `tsconfig.json`.
- JavaScript native browser ES6 mod
```html
<script type="module">
import * as paillierBigint from 'lib/index.browser.bundle.mod.js' // Use you actual path to the broser mod bundle
... // your code here
</script>
```
- JavaScript native browser IIFE
```html
<script src="../../lib/index.browser.bundle.js"></script> <!-- Use you actual path to the browser bundle -->
<script>
... // your code here
</script>
```
Then you could use, for instance, the following code:
```javascript
// import paillier in node.js
const paillier = require('paillier-bigint.js')
// import paillier in native JS
import * as paillier from 'paillier-bigint'
async function paillierTest() {
// (asynchronous) creation of a random private, public key pair for the Paillier cryptosystem
const {publicKey, privateKey} = await paillierBigint.generateRandomKeys(3072)
// (asynchronous) creation of a random private, public key pair for the Paillier cryptosystem
const {publicKey, privateKey} = await paillier.generateRandomKeys(3072)
// optionally, you can create your public/private keys from known parameters
const publicKey = new paillierBigint.PublicKey(n, g)
const privateKey = new paillierBigint.PrivateKey(lambda, mu, publicKey)
// optionally, you can create your public/private keys from known parameters
const publicKey = new paillier.PublicKey(n, g)
const privateKey = new paillier.PrivateKey(lambda, mu, publicKey)
// encrypt m
let c = publicKey.encrypt(m)
// encrypt m
let c = publicKey.encrypt(m)
// decrypt c
let d = privateKey.decrypt(c)
// decrypt c
let d = privateKey.decrypt(c)
// homomorphic addition of two ciphertexts (encrypted numbers)
let c1 = publicKey.encrypt(m1)
let c2 = publicKey.encrypt(m2)
let encryptedSum = publicKey.addition(c1, c2)
let sum = privateKey.decrypt(encryptedSum) // m1 + m2
// homomorphic addition of two ciphertexts (encrypted numbers)
let c1 = publicKey.encrypt(m1)
let c2 = publicKey.encrypt(m2)
let encryptedSum = publicKey.addition(c1, c2)
let sum = privateKey.decrypt(encryptedSum) // m1 + m2
// multiplication by k
let c1 = publicKey.encrypt(m1)
let encryptedMul = publicKey.multiply(c1, k)
let mul = privateKey.decrypt(encryptedMul) // k · m1
}
paillierTest()
// multiplication by k
let c1 = publicKey.encrypt(m1)
let encryptedMul = publicKey.multiply(c1, k)
let mul = privateKey.decrypt(encryptedMul) // k · m1
```
# JS Doc
## API reference documentation
## Classes
### Modules
<dl>
<dt><a href="#PublicKey">PublicKey</a></dt>
<dd></dd>
<dt><a href="#PrivateKey">PrivateKey</a></dt>
<dd></dd>
<dt><a href="#module_paillier-bigint">paillier-bigint</a></dt>
<dd><p>Paillier cryptosystem for both Node.js and native JS (browsers and webviews)</p>
</dd>
</dl>
## Constants
### Classes
<dl>
<dt><a href="#generateRandomKeys">generateRandomKeys</a> ⇒ <code><a href="#KeyPair">Promise.&lt;KeyPair&gt;</a></code></dt>
<dd><p>Generates a pair private, public key for the Paillier cryptosystem.</p>
</dd>
<dt><a href="#generateRandomKeysSync">generateRandomKeysSync</a> ⇒ <code><a href="#KeyPair">KeyPair</a></code></dt>
<dd><p>Generates a pair private, public key for the Paillier cryptosystem in synchronous mode.
Synchronous mode is NOT RECOMMENDED since it won&#39;t use workers and thus it&#39;ll be slower and may freeze thw window in browser&#39;s javascript.</p>
</dd>
<dt><a href="#PublicKey">PublicKey</a></dt>

@@ -144,160 +166,57 @@ <dd><p>Class for a Paillier public key</p>

## Typedefs
<a name="module_paillier-bigint"></a>
<dl>
<dt><a href="#KeyPair">KeyPair</a> : <code>Object</code></dt>
<dd></dd>
</dl>
### paillier-bigint
Paillier cryptosystem for both Node.js and native JS (browsers and webviews)
<a name="PublicKey"></a>
## PublicKey
**Kind**: global class
* [paillier-bigint](#module_paillier-bigint)
* [~generateRandomKeys([bitlength], [simplevariant])](#module_paillier-bigint..generateRandomKeys) ⇒ <code>Promise.&lt;KeyPair&gt;</code>
* [~generateRandomKeysSync([bitlength], [simplevariant])](#module_paillier-bigint..generateRandomKeysSync) ⇒ <code>KeyPair</code>
* [~KeyPair](#module_paillier-bigint..KeyPair) : <code>Object</code>
* [PublicKey](#PublicKey)
* [new PublicKey(n, g)](#new_PublicKey_new)
* [.bitLength](#PublicKey+bitLength) ⇒ <code>number</code>
* [.encrypt(m)](#PublicKey+encrypt) ⇒ <code>bigint</code>
* [.addition(...ciphertexts)](#PublicKey+addition) ⇒ <code>bigint</code>
* [.multiply(c, k)](#PublicKey+multiply) ⇒ <code>bigint</code>
<a name="module_paillier-bigint..generateRandomKeys"></a>
<a name="new_PublicKey_new"></a>
### new PublicKey(n, g)
Creates an instance of class PublicKey
| Param | Type | Description |
| --- | --- | --- |
| n | <code>bigint</code> | the public modulo |
| g | <code>bigint</code> \| <code>number</code> | the public generator |
<a name="PublicKey+bitLength"></a>
### publicKey.bitLength ⇒ <code>number</code>
Get the bit length of the public modulo
**Kind**: instance property of [<code>PublicKey</code>](#PublicKey)
**Returns**: <code>number</code> - - bit length of the public modulo
<a name="PublicKey+encrypt"></a>
### publicKey.encrypt(m) ⇒ <code>bigint</code>
Paillier public-key encryption
**Kind**: instance method of [<code>PublicKey</code>](#PublicKey)
**Returns**: <code>bigint</code> - - the encryption of m with this public key
| Param | Type | Description |
| --- | --- | --- |
| m | <code>bigint</code> | a bigint representation of a cleartext message |
<a name="PublicKey+addition"></a>
### publicKey.addition(...ciphertexts) ⇒ <code>bigint</code>
Homomorphic addition
**Kind**: instance method of [<code>PublicKey</code>](#PublicKey)
**Returns**: <code>bigint</code> - - the encryption of (m_1 + ... + m_2) with this public key
| Param | Type | Description |
| --- | --- | --- |
| ...ciphertexts | <code>bigint</code> | n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key |
<a name="PublicKey+multiply"></a>
### publicKey.multiply(c, k) ⇒ <code>bigint</code>
Pseudo-homomorphic Paillier multiplication
**Kind**: instance method of [<code>PublicKey</code>](#PublicKey)
**Returns**: <code>bigint</code> - - the encryption of k·m with this public key
| Param | Type | Description |
| --- | --- | --- |
| c | <code>bigint</code> | a number m encrypted with this public key |
| k | <code>bigint</code> \| <code>number</code> | either a bigint or a number |
<a name="PrivateKey"></a>
## PrivateKey
**Kind**: global class
* [PrivateKey](#PrivateKey)
* [new PrivateKey(lambda, mu, publicKey, [p], [q])](#new_PrivateKey_new)
* [.bitLength](#PrivateKey+bitLength) ⇒ <code>number</code>
* [.n](#PrivateKey+n) ⇒ <code>bigint</code>
* [.decrypt(c)](#PrivateKey+decrypt) ⇒ <code>bigint</code>
<a name="new_PrivateKey_new"></a>
### new PrivateKey(lambda, mu, publicKey, [p], [q])
Creates an instance of class PrivateKey
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| lambda | <code>bigint</code> | | |
| mu | <code>bigint</code> | | |
| publicKey | [<code>PublicKey</code>](#PublicKey) | | |
| [p] | <code>bigint</code> | <code></code> | a big prime |
| [q] | <code>bigint</code> | <code></code> | a big prime |
<a name="PrivateKey+bitLength"></a>
### privateKey.bitLength ⇒ <code>number</code>
Get the bit length of the public modulo
**Kind**: instance property of [<code>PrivateKey</code>](#PrivateKey)
**Returns**: <code>number</code> - - bit length of the public modulo
<a name="PrivateKey+n"></a>
### privateKey.n ⇒ <code>bigint</code>
Get the public modulo n=p·q
**Kind**: instance property of [<code>PrivateKey</code>](#PrivateKey)
**Returns**: <code>bigint</code> - - the public modulo n=p·q
<a name="PrivateKey+decrypt"></a>
### privateKey.decrypt(c) ⇒ <code>bigint</code>
Paillier private-key decryption
**Kind**: instance method of [<code>PrivateKey</code>](#PrivateKey)
**Returns**: <code>bigint</code> - - the decryption of c with this private key
| Param | Type | Description |
| --- | --- | --- |
| c | <code>bigint</code> | a bigint encrypted with the public key |
<a name="generateRandomKeys"></a>
## generateRandomKeys ⇒ [<code>Promise.&lt;KeyPair&gt;</code>](#KeyPair)
#### paillier-bigint~generateRandomKeys([bitlength], [simplevariant]) ⇒ <code>Promise.&lt;KeyPair&gt;</code>
Generates a pair private, public key for the Paillier cryptosystem.
**Kind**: global constant
**Returns**: [<code>Promise.&lt;KeyPair&gt;</code>](#KeyPair) - - a promise that resolves to a [KeyPair](#KeyPair) of public, private keys
**Kind**: inner method of [<code>paillier-bigint</code>](#module_paillier-bigint)
**Returns**: <code>Promise.&lt;KeyPair&gt;</code> - - a promise that resolves to a [KeyPair](KeyPair) of public, private keys
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [bitLength] | <code>number</code> | <code>3072</code> | the bit length of the public modulo |
| [bitlength] | <code>number</code> | <code>3072</code> | the bit length of the public modulo |
| [simplevariant] | <code>boolean</code> | <code>false</code> | use the simple variant to compute the generator (g=n+1) |
<a name="generateRandomKeysSync"></a>
<a name="module_paillier-bigint..generateRandomKeysSync"></a>
## generateRandomKeysSync ⇒ [<code>KeyPair</code>](#KeyPair)
#### paillier-bigint~generateRandomKeysSync([bitlength], [simplevariant]) ⇒ <code>KeyPair</code>
Generates a pair private, public key for the Paillier cryptosystem in synchronous mode.
Synchronous mode is NOT RECOMMENDED since it won't use workers and thus it'll be slower and may freeze thw window in browser's javascript.
**Kind**: global constant
**Returns**: [<code>KeyPair</code>](#KeyPair) - - a [KeyPair](#KeyPair) of public, private keys
**Kind**: inner method of [<code>paillier-bigint</code>](#module_paillier-bigint)
**Returns**: <code>KeyPair</code> - - a [KeyPair](KeyPair) of public, private keys
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [bitLength] | <code>number</code> | <code>4096</code> | the bit length of the public modulo |
| [bitlength] | <code>number</code> | <code>4096</code> | the bit length of the public modulo |
| [simplevariant] | <code>boolean</code> | <code>false</code> | use the simple variant to compute the generator (g=n+1) |
<a name="module_paillier-bigint..KeyPair"></a>
#### paillier-bigint~KeyPair : <code>Object</code>
**Kind**: inner typedef of [<code>paillier-bigint</code>](#module_paillier-bigint)
**Properties**
| Name | Type | Description |
| --- | --- | --- |
| publicKey | [<code>PublicKey</code>](#PublicKey) | a Paillier's public key |
| privateKey | [<code>PrivateKey</code>](#PrivateKey) | the associated Paillier's private key |
<a name="PublicKey"></a>
## PublicKey
### PublicKey
Class for a Paillier public key
**Kind**: global constant
**Kind**: global class

@@ -313,3 +232,3 @@ * [PublicKey](#PublicKey)

### new PublicKey(n, g)
#### new PublicKey(n, g)
Creates an instance of class PublicKey

@@ -321,7 +240,7 @@

| n | <code>bigint</code> | the public modulo |
| g | <code>bigint</code> \| <code>number</code> | the public generator |
| g | <code>bigint</code> | the public generator |
<a name="PublicKey+bitLength"></a>
### publicKey.bitLength ⇒ <code>number</code>
#### publicKey.bitLength ⇒ <code>number</code>
Get the bit length of the public modulo

@@ -333,3 +252,3 @@

### publicKey.encrypt(m) ⇒ <code>bigint</code>
#### publicKey.encrypt(m) ⇒ <code>bigint</code>
Paillier public-key encryption

@@ -346,3 +265,3 @@

### publicKey.addition(...ciphertexts) ⇒ <code>bigint</code>
#### publicKey.addition(...ciphertexts) ⇒ <code>bigint</code>
Homomorphic addition

@@ -359,3 +278,3 @@

### publicKey.multiply(c, k) ⇒ <code>bigint</code>
#### publicKey.multiply(c, k) ⇒ <code>bigint</code>
Pseudo-homomorphic Paillier multiplication

@@ -373,6 +292,6 @@

## PrivateKey
### PrivateKey
Class for Paillier private keys.
**Kind**: global constant
**Kind**: global class

@@ -387,3 +306,3 @@ * [PrivateKey](#PrivateKey)

### new PrivateKey(lambda, mu, publicKey, [p], [q])
#### new PrivateKey(lambda, mu, publicKey, [p], [q])
Creates an instance of class PrivateKey

@@ -402,3 +321,3 @@

### privateKey.bitLength ⇒ <code>number</code>
#### privateKey.bitLength ⇒ <code>number</code>
Get the bit length of the public modulo

@@ -410,3 +329,3 @@

### privateKey.n ⇒ <code>bigint</code>
#### privateKey.n ⇒ <code>bigint</code>
Get the public modulo n=p·q

@@ -418,3 +337,3 @@

### privateKey.decrypt(c) ⇒ <code>bigint</code>
#### privateKey.decrypt(c) ⇒ <code>bigint</code>
Paillier private-key decryption

@@ -429,12 +348,1 @@

<a name="KeyPair"></a>
## KeyPair : <code>Object</code>
**Kind**: global typedef
**Properties**
| Name | Type | Description |
| --- | --- | --- |
| publicKey | [<code>PublicKey</code>](#PublicKey) | a Paillier's public key |
| privateKey | [<code>PrivateKey</code>](#PrivateKey) | the associated Paillier's private key |

@@ -5,99 +5,7 @@ export type KeyPair = {

*/
publicKey: {
n: bigint;
_n2: bigint;
g: bigint;
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
readonly bitLength: number;
/**
* Paillier public-key encryption
*
* @param {bigint} m - a bigint representation of a cleartext message
*
* @returns {bigint} - the encryption of m with this public key
*/
encrypt(m: bigint): bigint;
/**
* Homomorphic addition
*
* @param {...bigint} ciphertexts - n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key
*
* @returns {bigint} - the encryption of (m_1 + ... + m_2) with this public key
*/
addition(...ciphertexts: bigint[]): bigint;
/**
* Pseudo-homomorphic Paillier multiplication
*
* @param {bigint} c - a number m encrypted with this public key
* @param {bigint | number} k - either a bigint or a number
*
* @returns {bigint} - the encryption of k·m with this public key
*/
multiply(c: bigint, k: number | bigint): bigint;
};
publicKey: PublicKey;
/**
* - the associated Paillier's private key
*/
privateKey: {
lambda: bigint;
mu: bigint;
_p: bigint;
_q: bigint;
publicKey: {
n: bigint;
_n2: bigint;
g: bigint;
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
readonly bitLength: number;
/**
* Paillier public-key encryption
*
* @param {bigint} m - a bigint representation of a cleartext message
*
* @returns {bigint} - the encryption of m with this public key
*/
encrypt(m: bigint): bigint;
/**
* Homomorphic addition
*
* @param {...bigint} ciphertexts - n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key
*
* @returns {bigint} - the encryption of (m_1 + ... + m_2) with this public key
*/
addition(...ciphertexts: bigint[]): bigint;
/**
* Pseudo-homomorphic Paillier multiplication
*
* @param {bigint} c - a number m encrypted with this public key
* @param {bigint | number} k - either a bigint or a number
*
* @returns {bigint} - the encryption of k·m with this public key
*/
multiply(c: bigint, k: number | bigint): bigint;
};
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
readonly bitLength: number;
/**
* Get the public modulo n=p·q
* @returns {bigint} - the public modulo n=p·q
*/
readonly n: bigint;
/**
* Paillier private-key decryption
*
* @param {bigint} c - a bigint encrypted with the public key
*
* @returns {bigint} - the decryption of c with this private key
*/
decrypt(c: bigint): bigint;
};
privateKey: PrivateKey;
};

@@ -107,138 +15,108 @@ /**

*/
export const PrivateKey: {
new (lambda: bigint, mu: bigint, publicKey: {
n: bigint;
_n2: bigint;
g: bigint;
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
readonly bitLength: number;
/**
* Paillier public-key encryption
*
* @param {bigint} m - a bigint representation of a cleartext message
*
* @returns {bigint} - the encryption of m with this public key
*/
encrypt(m: bigint): bigint;
/**
* Homomorphic addition
*
* @param {...bigint} ciphertexts - n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key
*
* @returns {bigint} - the encryption of (m_1 + ... + m_2) with this public key
*/
addition(...ciphertexts: bigint[]): bigint;
/**
* Pseudo-homomorphic Paillier multiplication
*
* @param {bigint} c - a number m encrypted with this public key
* @param {bigint | number} k - either a bigint or a number
*
* @returns {bigint} - the encryption of k·m with this public key
*/
multiply(c: bigint, k: number | bigint): bigint;
}, p?: bigint, q?: bigint): {
lambda: bigint;
mu: bigint;
_p: bigint;
_q: bigint;
publicKey: {
n: bigint;
_n2: bigint;
g: bigint;
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
readonly bitLength: number;
/**
* Paillier public-key encryption
*
* @param {bigint} m - a bigint representation of a cleartext message
*
* @returns {bigint} - the encryption of m with this public key
*/
encrypt(m: bigint): bigint;
/**
* Homomorphic addition
*
* @param {...bigint} ciphertexts - n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key
*
* @returns {bigint} - the encryption of (m_1 + ... + m_2) with this public key
*/
addition(...ciphertexts: bigint[]): bigint;
/**
* Pseudo-homomorphic Paillier multiplication
*
* @param {bigint} c - a number m encrypted with this public key
* @param {bigint | number} k - either a bigint or a number
*
* @returns {bigint} - the encryption of k·m with this public key
*/
multiply(c: bigint, k: number | bigint): bigint;
};
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
readonly bitLength: number;
/**
* Get the public modulo n=p·q
* @returns {bigint} - the public modulo n=p·q
*/
readonly n: bigint;
/**
* Paillier private-key decryption
*
* @param {bigint} c - a bigint encrypted with the public key
*
* @returns {bigint} - the decryption of c with this private key
*/
decrypt(c: bigint): bigint;
};
};
export class PrivateKey {
/**
* Creates an instance of class PrivateKey
*
* @param {bigint} lambda
* @param {bigint} mu
* @param {PublicKey} publicKey
* @param {bigint} [p = null] - a big prime
* @param {bigint} [q = null] - a big prime
*/
constructor(lambda: bigint, mu: bigint, publicKey: PublicKey, p?: bigint, q?: bigint);
lambda: bigint;
mu: bigint;
_p: bigint;
_q: bigint;
publicKey: PublicKey;
/**
* Get the bit length of the public modulo
* @returns {number} - bit length of the public modulo
*/
get bitLength(): number;
/**
* Get the public modulo n=p·q
* @returns {bigint} - the public modulo n=p·q
*/
get n(): bigint;
/**
* Paillier private-key decryption
*
* @param {bigint} c - a bigint encrypted with the public key
*
* @returns {bigint} - the decryption of c with this private key
*/
decrypt(c: bigint): bigint;
}
/**
* Class for a Paillier public key
*/
export const PublicKey: {
new (n: bigint, g: number | bigint): {
n: bigint;
_n2: bigint;
g: bigint;
/**
* Get the bit length of the public modulo
* @return {number} - bit length of the public modulo
*/
readonly bitLength: number;
/**
* Paillier public-key encryption
*
* @param {bigint} m - a bigint representation of a cleartext message
*
* @returns {bigint} - the encryption of m with this public key
*/
encrypt(m: bigint): bigint;
/**
* Homomorphic addition
*
* @param {...bigint} ciphertexts - n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key
*
* @returns {bigint} - the encryption of (m_1 + ... + m_2) with this public key
*/
addition(...ciphertexts: bigint[]): bigint;
/**
* Pseudo-homomorphic Paillier multiplication
*
* @param {bigint} c - a number m encrypted with this public key
* @param {bigint | number} k - either a bigint or a number
*
* @returns {bigint} - the encryption of k·m with this public key
*/
multiply(c: bigint, k: number | bigint): bigint;
};
};
export function generateRandomKeys(bitLength$1?: number, simpleVariant?: boolean): Promise<KeyPair>;
export function generateRandomKeysSync(bitLength$1?: number, simpleVariant?: boolean): KeyPair;
export class PublicKey {
/**
* Creates an instance of class PublicKey
* @param {bigint} n - the public modulo
* @param {bigint} g - the public generator
*/
constructor(n: bigint, g: bigint);
n: bigint;
_n2: bigint;
g: bigint;
/**
* Get the bit length of the public modulo
* @returns {number} - bit length of the public modulo
*/
get bitLength(): number;
/**
* Paillier public-key encryption
*
* @param {bigint} m - a bigint representation of a cleartext message
*
* @returns {bigint} - the encryption of m with this public key
*/
encrypt(m: bigint): bigint;
/**
* Homomorphic addition
*
* @param {...bigint} ciphertexts - n >= 2 ciphertexts (c_1,..., c_n) that are the encryption of (m_1, ..., m_n) with this public key
*
* @returns {bigint} - the encryption of (m_1 + ... + m_2) with this public key
*/
addition(...ciphertexts: bigint[]): bigint;
/**
* Pseudo-homomorphic Paillier multiplication
*
* @param {bigint} c - a number m encrypted with this public key
* @param {bigint | number} k - either a bigint or a number
*
* @returns {bigint} - the encryption of k·m with this public key
*/
multiply(c: bigint, k: number | bigint): bigint;
}
/**
* Paillier cryptosystem for both Node.js and native JS (browsers and webviews)
* @module paillier-bigint
*/
/**
* @typedef {Object} KeyPair
* @property {PublicKey} publicKey - a Paillier's public key
* @property {PrivateKey} privateKey - the associated Paillier's private key
*/
/**
* Generates a pair private, public key for the Paillier cryptosystem.
*
* @param {number} [bitlength = 3072] - the bit length of the public modulo
* @param {boolean} [simplevariant = false] - use the simple variant to compute the generator (g=n+1)
*
* @returns {Promise<KeyPair>} - a promise that resolves to a {@link KeyPair} of public, private keys
*/
export function generateRandomKeys(bitlength?: number, simpleVariant?: boolean): Promise<KeyPair>;
/**
* Generates a pair private, public key for the Paillier cryptosystem in synchronous mode.
* Synchronous mode is NOT RECOMMENDED since it won't use workers and thus it'll be slower and may freeze thw window in browser's javascript.
*
* @param {number} [bitlength = 4096] - the bit length of the public modulo
* @param {boolean} [simplevariant = false] - use the simple variant to compute the generator (g=n+1)
*
* @returns {KeyPair} - a {@link KeyPair} of public, private keys
*/
export function generateRandomKeysSync(bitlength?: number, simpleVariant?: boolean): KeyPair;
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc