Created
January 13, 2016 23:38
-
-
Save vidul-nikolaev-petrov/8f01ec4bd2e06e373c32 to your computer and use it in GitHub Desktop.
PKI & AES (en/de)cryption, based on the JS Forge crypto library
This file contains 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
/** | |
* @author Vidul Nikolaev Petrov | |
* @summary helper methods for PKI / AES usage, based on the JS Forge crypto library. | |
*/ | |
function s8Crypto(bits) { | |
var hexToBytes = forge.util.hexToBytes, | |
bytesToHex = forge.util.bytesToHex; | |
this.pki = {}; | |
this.aes = {}; | |
this.initPKI = function () { | |
var keys = forge.pki.rsa.generateKeyPair({ | |
bits: bits || 1024, | |
e: 0x10001, | |
}), | |
key_pub = forge.pki.publicKeyToPem(keys.publicKey), | |
key_priv = forge.pki.privateKeyToPem(keys.privateKey); | |
this.pki.keys = keys; | |
this.pki.pems = { | |
public: key_pub, | |
private: key_priv, | |
}; | |
return this; | |
}; | |
this.encrypt = function (pki_public_key, data) { | |
var key = forge.random.getBytesSync(16), | |
iv = forge.random.getBytesSync(16), | |
cipher = forge.cipher.createCipher('AES-CBC', key), | |
public_key = forge.pki.publicKeyFromPem(pki_public_key), | |
encrypted; | |
cipher.start({ | |
iv: iv, | |
}); | |
cipher.update(forge.util.createBuffer(data, 'utf8')); | |
cipher.finish(); | |
encrypted = forge.util.encodeUtf8(cipher.output.getBytes()); | |
encrypted = forge.util.encode64(encrypted); | |
return { | |
encrypted: encrypted, | |
iv: bytesToHex(public_key.encrypt(iv)), | |
key: bytesToHex(public_key.encrypt(key)), | |
}; | |
}; | |
this.decrypt = function (data) { | |
var encrypted = data.encrypted, | |
iv = this.pki.keys.privateKey.decrypt(hexToBytes(data.iv)), | |
key = this.pki.keys.privateKey.decrypt(hexToBytes(data.key)), | |
decipher = forge.cipher.createDecipher('AES-CBC', key); | |
encrypted = forge.util.decode64(encrypted); | |
encrypted = forge.util.decodeUtf8(encrypted); | |
encrypted = forge.util.createBuffer(encrypted); | |
decipher.start({ | |
iv: iv, | |
}); | |
decipher.update(encrypted); | |
decipher.finish(); | |
return decipher; | |
}; | |
this.getHumanData = function (decipher) { | |
return decipher.output.toString('utf8'); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment