Last active
April 18, 2018 06:48
-
-
Save noman-land/a65520aa4f2ce7ba3bf9f13d20016346 to your computer and use it in GitHub Desktop.
Example of additive and multiplicative homomorphic encryption
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reference: https://radicalrafi.github.io/posts/homomorphic-encryption/ | |
// npm i --save big-integer | |
const bigInt = require('big-integer'); | |
const L = (x, n) => x.minus(1).divide(n); | |
function createEncryptor({ n, g }) { | |
return (m, r) => g.pow(m).times(r.pow(n)).mod(n.pow(2)); | |
} | |
function createDecryptor({ lambda, mu }, n) { | |
return c => L(c.pow(lambda).mod(n.pow(2)), n).times(mu).mod(n); | |
} | |
// Two large primes | |
const p = new bigInt(97); | |
const q = new bigInt(29); | |
const n = p.times(q); | |
const g = n.plus(1); | |
const pubKey = { n, g }; | |
const lambda = bigInt.lcm(p.minus(1), q.minus(1)); | |
const mu = lambda.modInv(n); | |
const privKey = { lambda, mu }; | |
const encrypt = createEncryptor(pubKey); | |
const decrypt = createDecryptor(privKey, pubKey.n); | |
const message = new bigInt(42); | |
const random = new bigInt(23); | |
const message2 = new bigInt(101); | |
const random2 = new bigInt(37); | |
const cipherText = encrypt(message, random); | |
const cipherText2 = encrypt(message2, random2); | |
const messageSum = decrypt(cipherText.times(cipherText2)); | |
const messageProduct = decrypt(cipherText2.pow(7)); | |
console.log(messageSum); | |
// D(E(message) * E(message2)) = message + message2 = 143 | |
console.log(messageProduct); | |
// D(E(message2)^7) = message2 * 7 = 707 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment