UNPKG

runtime-node-crypto

Version:
84 lines (63 loc) 2.01 kB
'use strict'; var Hash = require('./lib/hash'); var ciphers = require('./lib/cipher'); /* Since sodium uses crypto.randomBytes: A) This module will ONLY work when aliased to 'crypto' in runtimeify, AND B) It MUST expose randomBytes BEFORE requiring sodium-browserify */ module.exports = { randomBytes: function(length) { if (!length) { throw new Error('runtime-node-crytpo: length must be provided.'); } if (length === 0) { throw new Error('runtime-node-crytpo: length must be greater than 0.'); } var u8 = runtime.random.getRandomValues(length); return new Buffer(u8); }, getRandomValues: runtime.random.getRandomValues // <-- for diffie-hellman and browserify-sign to not complain }; global.crypto = module.exports; // <-- again, for diffie-hellman and browserify-sign to not complain // Now we can use all the goodies! const sodium = require('sodium-browserify'); // Just copy them to module.exports... for (let k in sodium) { module.exports[k] = sodium[k]; } module.exports.createHash = function(alg, opt) { return new Hash(alg, opt); } module.exports.Hash = Hash; var dh = require('diffie-hellman'); // Copy diffie-hellman for (let k in dh) { module.exports[k] = dh[k]; } var bs = require('browserify-sign'); // Copy browserify-sign for (let k in bs) { module.exports[k] = bs[k]; } module.exports.createCipher = function(cipher, key) { return new ciphers.Cipher(cipher, key); } module.exports.createCipheriv = function(cipher, key, iv) { return new ciphers.Cipheriv(cipher, key, iv); } module.exports.createDecipher = function(cipher, key) { return new ciphers.Decipher(cipher, key); } module.exports.createDecipheriv = function(cipher, key, iv) { return new ciphers.Decipheriv(cipher, key, iv); } // Copy the cipher classes for (let k in ciphers) { module.exports[k] = ciphers[k]; } var ch = require('create-hmac'); // Copy create-hmac for (let k in ch) { module.exports[k] = ch[k]; } global.crypto = module.exports;