UNPKG

runtime-node-crypto

Version:
93 lines (85 loc) 2.16 kB
'use strict'; var ba = require('browserify-aes'); var base64 = require('base64-js'); var cjs = require('crypto-js'); class Cipher { constructor(cipher, key) { this._cipher = cipher; this._key = key; this._cont = ''; this._handle = (cipher.substr(0, 3) === 'aes') ? new ba.Cipher(cipher, key) : null; } update(cont, enc) { if (this._handle !== null) { this._handle.update(cont, enc); return this; } else { if (enc !== 'base64') { cont = new Buffer(cont, enc).toString('utf8'); this._cont += cont; return this; } this._cont += base64.toByteArray(cont).toString('utf8'); return this; } return this; } setAutoPadding(padd) { // do nothing, padding is always off. // TODO: add padding option. } final(enc) { if (this._handle !== null) { return this._handle.final(enc); } else { var cipherString = cjs.RC4.encrypt(this._cont, this._key); var buffer = new Buffer(String(cipherString), 'binary'); if (enc) { if (enc !== 'base64') { return buffer.toString(enc); } return base64.fromByteArray(buffer); } else { return buffer; } } } } class Cipheriv extends Cipher { constructor(cipher, key, iv) { super(cipher, key); this._key = key + iv; } } class Decipher extends Cipher { constructor(cipher, key) { super(cipher, key); } final(enc) { if (this._handle !== null) { return this._handle.final(enc); } else { var cipherString = cjs.RC4.decrypt(this._cont, this._key); var buffer = new Buffer(String(cipherString), 'hex'); if (enc) { if (enc !== 'base64') { return buffer.toString(enc); } return base64.fromByteArray(buffer); } else { return buffer; } } } } class Decipheriv extends Decipher { constructor(cipher, key, iv) { super(cipher, key); this._key = key + iv; } } module.exports = {}; module.exports.Cipher = Cipher; module.exports.Cipheriv = Cipheriv; module.exports.Decipher = Decipher; module.exports.Decipheriv = Decipheriv;