Пример #1
0
    Crypt.prototype.decrypt = function (data, f)
    {
        "use strict";

        var key, decipher, ddata, jdata;

        try
        {
            Crypt.check_version(data);

            if (this.key.is_private)
            {
                key = crypto.privateDecrypt(
                {
                    key: this.key.key,
                    padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
                }, this.encoding ? new Buffer(data.ekey, this.encoding) :
                                   data.ekey);
            }
            else if (!this.key.is_public)
            {
                key = this.key.key || this.key;
            }
            else
            {
                throw new Error("can't decrypt using public key");
            }

            decipher = crypto.createDecipheriv(
                    'AES-128-CBC',
                    key,
                    this.encoding ? new Buffer(data.iv, this.encoding) :
                                    data.iv);
            decipher.setAutoPadding(this.options.pad);

            ddata = decipher.update(data.data, this.encoding);
            ddata = Buffer.concat([ddata, decipher.final()]);

            if (this.options.check)
            {
                jdata = ddata.slice(Crypt._SHA256_SIZE);

                if (!Crypt._buffer_equal(crypto.createHash('sha256')
                                            .update(jdata)
                                            .digest(),
                                         ddata.slice(0, Crypt._SHA256_SIZE)))
                {
                    throw new Error('digest mismatch');
                }
            }
            else
            {
                jdata = ddata;
            }

            jdata = this.parse(jdata);
        }
        catch (ex)
        {
            return f.call(this, Crypt._ensure_error(ex));
        }

        f.call(this, null, jdata);
    };
Пример #2
0
var mkDecipher = function(self) {
  if (self.iv)
    return crypto.createDecipheriv(self.algorithm, self.key, self.iv);
  return crypto.createDecipher(self.algorithm, self.key);
};
Пример #3
0
helper.decodePassword = function( password, key ) {
    var decipher = crypto.createDecipheriv( "bf-ecb", Buffer( key, "base64" ), '' );
    var result = decipher.update( password, "base64", "utf8" );
    result += decipher.final( "utf8" );
    return result;
};
Пример #4
0
 decrypt: function(password) {
     var decipher = crypto.createDecipheriv('aes-256-cbc', this.config.aeskey, this.config.aesiv);
     var dec = decipher.update(password,'base64','utf8');
     dec += decipher.final('utf8');
     return dec;
 },
Пример #5
0
Session.prototype.getPacket = function (packet) {
  var type = packet.getType();
  console.log('<< Type', type, '-', packet.payload.length, 'bytes');
  switch (type) {
    case 1: // disconnect
      var code = packet.readUInt32(),
          msg = packet.readString();
      console.log('Client disconnected:', msg, '('+code+')');
      break;
    
    case 20: // kexinit
      this.hashIn.push(packet.payload);
      this.hashIn.push(composePacket([{byte: 20}, {raw: this.cookie}, ['diffie-hellman-group-exchange-sha256'], ['ssh-rsa'], ['aes256-ctr'], ['aes256-ctr'], ['hmac-md5'], ['hmac-md5'], ['none'], ['none'], [], [], false, {uint32: 0}]));
      this.hashIn.push(hostPub);
      
      this.kex = {
        cookie: packet.readBuffer(16),
        kexAlgs:     packet.readList(),
        hostKeyAlgs: packet.readList(),
        encAlgs:    [packet.readList(), packet.readList()],
        macAlgs:    [packet.readList(), packet.readList()],
        cprAlgs:    [packet.readList(), packet.readList()],
        langs:      [packet.readList(), packet.readList()],
        firstKexFollows: packet.readBool()};
      break;
    
    case 30: // older 34
      this.dhflags = { n:   packet.readUInt32() };
      this.hashIn.push({uint32: this.dhflags.n});
      this.dh = crypto.getDiffieHellman('modp2');
      
      // SSH_MSG_KEX_DH_GEX_GROUP
      this.hashIn.push({mpint: this.dh.getPrime()});
      this.hashIn.push({mpint: new Buffer([2])});
      this.sendPay([{byte: 31}, {mpint: this.dh.getPrime()}, {mpint: new Buffer([2])}]);
      this.dh.generateKeys();
      break;
    
    case 34: // SSH_MSG_KEX_DH_GEX_REQUEST
      this.dhflags = {
        min: packet.readUInt32(),
        n:   packet.readUInt32(),
        max: packet.readUInt32()};
      this.hashIn.push({uint32: this.dhflags.min});
      this.hashIn.push({uint32: this.dhflags.n});
      this.hashIn.push({uint32: this.dhflags.max});
      this.dh = crypto.getDiffieHellman('modp2');
      
      // SSH_MSG_KEX_DH_GEX_GROUP
      this.hashIn.push({mpint: this.dh.getPrime()});
      this.hashIn.push({mpint: new Buffer([2])});
      this.sendPay([{byte: 31}, {mpint: this.dh.getPrime()}, {mpint: new Buffer([2])}]);
      this.dh.generateKeys();
      break;
    
    case 32: // SSH_MSG_KEX_DH_GEX_INIT
      this.e = packet.readMpint();
      this.dh.secret = this.dh.computeSecret(this.e);
      
      this.hashIn.push({mpint: this.e});
      this.hashIn.push({mpint: this.dh.getPublicKey()});
      this.hashIn.push({mpint: this.dh.secret});
      
      var sha = crypto.createHash('sha256');
      sha.write(composePacket(this.hashIn));
      this.session = sha.digest();
      this.sendPay([{byte: 33}, hostPub, {mpint: this.dh.getPublicKey()}, this.signBuffer(this.session)]);
      break;
    
    case 21: // SSH_MSG_NEWKEYS okay bro, keys are good, let's goooo
      this.sendPay([{byte: 21}]);
      this.keyson = true;
      
      //console.log(keyize('C').digest('hex'));
      this.deciph = crypto.createDecipheriv('aes-256-ctr', this.keyize('C').digest(), this.keyize('A').digest().slice(0,16));
      this.cipher = crypto.createCipheriv  ('aes-256-ctr', this.keyize('D').digest(), this.keyize('B').digest().slice(0,16));
      
      this.macC = this.keyize('E').digest();
      this.macS = this.keyize('F').digest();
      this.macLen = 16;
      break;
    
    case 5: // SSH_MSG_SERVICE_REQUEST
      var service = packet.readString();
      console.log('Client requested', service);
      if (service == 'ssh-userauth') {
        this.sendPay([{byte: 6}, service]); // SSH_MSG_SERVICE_ACCEPT
      } else {
        this.sendPay([{byte: 1}, {byte: 0}, 'wtf dude']);
      }
      break;
    
    case 50: // SSH_MSG_USERAUTH_REQUEST
      this.user = packet.readString();
      var service = packet.readString();
      var method = packet.readString(); // plus more
      console.log(this.user, service, method);
      if (method == 'none') {
        if (true) { // anonymous server?
          this.sendPay([{byte: 52}]); // SSH_MSG_USERAUTH_SUCCESS
        } else {
          this.sendPay([{byte: 51}, ['publickey', 'keyboard-interactive'], false]); // SSH_MSG_USERAUTH_FAILURE
        };
      } else if (method == 'keyboard-interactive') {
        var lang = packet.readString();
        var submethods = packet.readString();
        console.log({lang:lang,submethods:submethods});
        if (this.keys.length) {
          this.sendPay([{byte: 60}, 'Log in to Gitbus', "Your "+this.keys.length+" public keys were not recognized by gitbus. If you'd like to add one, please log in.", 'en-US', {uint32:2}, 'Username: '******'Password: '******'publickey'], false]); // SSH_MSG_USERAUTH_FAILURE
        }
      } else if (method == 'password') {
        this.sendPay([{byte: 53}, 'Welcome to Gitbus!\r\n', 'en-US']);
        this.sendPay([{byte: 53}, "I don't recognize your SSH public key.\r\n", 'en-US']);
        this.sendPay([{byte: 53}, "If you'd like to pair it to " + user + ", enter your gitbus password now.\r\n", 'en-US']);
      } else if (method == 'publickey') {
        var signed = packet.readBool();
        var key = {
          alg: packet.readString(),
          blob: packet.readString()};
        console.log(key);
        this.keys.push(key);
        this.sendPay([{byte: 51}, ['publickey', 'keyboard-interactive'], false]); // SSH_MSG_USERAUTH_FAILURE
      } else {
        this.sendPay([{byte: 51}, ['publickey', 'keyboard-interactive', 'password'], false]); // SSH_MSG_USERAUTH_FAILURE
      };
      break;
    
    case 61: // SSH_MSG_USERAUTH_INFO_RESPONSE
      var count = packet.readUInt32();
      if (this.stage) {
//          var keynum = packet.readString();
//          var comment = packet.readString();
        this.sendPay([{byte: 53}, 'Key successfully added.\r\n', 'en-US']);
        this.sendPay([{byte: 52}]); // SSH_MSG_USERAUTH_INFO_REQUEST
      } else {
        var username = packet.readString();
        var password = packet.readString();
        if (keys.length > 1) {
          this.sendPay([{byte: 60}, 'Select public key to add', keys.map(function(key,i){return ''+i+': '+key.alg+' '+(new Buffer(key.blob).toString('base64')).slice(0,60)+'...'}).join('\r\n'), 'en-US', {uint32:2}, 'Key number: ', true, 'Key label/comment: ', true]); // SSH_MSG_USERAUTH_INFO_REQUEST
        } else {
          this.sendPay([{byte: 60}, 'Add key to Gitbus', keys[0].alg+' '+(new Buffer(keys[0].blob).toString('base64')).slice(0,60)+'... will be added to your Gitbus.', 'en-US', {uint32:1}, 'Key label/comment: ', true]); // SSH_MSG_USERAUTH_INFO_REQUEST
        };
        this.stage = true;
      };
      break;
    
    case 80: // SSH_MSG_GLOBAL_REQUEST
      var type = packet.readString();
      var wantReply = packet.readBool();
      
      if (type == '*****@*****.**') {
        console.log('Client is still alive!');
        this.sendPay([{byte: 81}]); // SSH_MSG_REQUEST_SUCCESS
      } else {
        console.log('Global requested', type, 'for but idk');
        if (wantReply)
          this.sendPay([{byte: 82}]); // SSH_MSG_REQUEST_FAILURE
      };
      break;
    
    case 90: // SSH_MSG_CHANNEL_OPEN
      var channel = {
        type: packet.readString(),
        sender: packet.readUInt32(),
        initSize: packet.readUInt32(),
        maxSize: packet.readUInt32()}; // plus more
      console.log(channel);
        
      this.sendPay([{byte: 91}, {uint32: channel.sender}, {uint32: channel.sender}, {uint32: channel.initSize}, {uint32: channel.maxSize}]); // SSH_MSG_CHANNEL_OPEN_CONFIRMATION
      break;
    
    case 96: // SSH_MSG_CHANNEL_EOF
      if (this.proc) proc.stdin.end();
    case 97: // SSH_MSG_CHANNEL_CLOSE
      break;
    
    case 98: // SSH_MSG_CHANNEL_REQUEST
      var recip = packet.readUInt32();
      var type = packet.readString();
      var wantReply = packet.readBool();
      // plus more
      
      if (this.emit('channelreq', recip, type, wantReply)) {
        // handled
      } else if (type == 'env') {
        console.log('Environment:', packet.readString(), '=', packet.readString());
      } else if (type == 'pty-req') {
        var pty = {
          term: packet.readString(),
          widthC: packet.readUInt32(),
          heightC: packet.readUInt32(),
          widthP: packet.readUInt32(),
          heightP: packet.readUInt32(),
          modes: packet.readString()};
        
        console.log(wantReply, pty);
        this.sendPay([{byte: 99}, {uint32: recip}]); // SSH_MSG_CHANNEL_SUCCESS
      } else {
        console.log('Requested', type, 'for', recip, '... but idk');
        if (wantReply)
          that.sendPay([{byte: 98}, {uint32: recip}]); // SSH_MSG_CHANNEL_FAILURE
      };
      break;
    
    case 93: // SSH_MSG_CHANNEL_WINDOW_ADJUST
      break;
    
    case 94: // SSH_MSG_CHANNEL_DATA
      var chan = packet.readUInt32();
      var data = packet.readString();
      console.log(chan, data);
      if (this.proc) {
        if (data == '\u0003' || data == 'q') {
          this.proc.kill('SIGINT');
          this.proc = null;
        } else {
          while (data.length) {
            this.proc.stdin.write(data.slice(0, 512));
            data = data.slice(512);
          };
        };
      } else {
        if (data == '\u0004') {
          this.sendPay([{byte: 94}, {uint32: chan}, 'Hit q to exit\r\n']);
        } else if (data == 'q') {
          this.sendPay([{byte: 98}, {uint32: chan}, 'exit-status', false, {uint32: 0}]); // SSH_MSG_CHANNEL_REQUEST
          this.sendPay([{byte: 97}, {uint32: chan}]);
        } else {
          this.sendPay([{byte: 94}, {uint32: chan}, 'You hit ' + data + '\r\n']);
        }
      };
      
      break;
    
    default:
      console.log('Unimpl packet', type, packet.payload, packet.payload.toString());
      process.exit();
  };
};
Пример #6
0
exports.createDecipher = function(secret) {
    return crypto.createDecipheriv(AES256, new Buffer(secret.k, BASE64), new Buffer(secret.v, BASE64));
};
Пример #7
0
var DecryptAES = function(enc){
	var decipher = crypto.createDecipheriv('aes256', cryptkey, iv);		// 고정키 복호화 도구
	var ret = decipher.update(enc, 'hex', 'utf8')+decipher.final('utf8');
	return ret.replace(/ +$/g,'');
}
Пример #8
0
 assert.throws(() => {
   crypto.createDecipheriv('aes-256-ccm',
                           'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8',
                           'qkuZpJWCewa6S');
 }, /^Error: authTagLength required for aes-256-ccm$/);
 () => crypto.createDecipheriv(null),
Пример #10
0
var Body = require('../../src/components/body');
var digest = require('../../src/md5');
var fs = require('fs');
var crypto = require('crypto');
var algorithm = 'aes128';

var testFile = fs.readFileSync(__dirname + '/../assets/demo.db');
var key = digest('wYl0$uberpass');
var iv = testFile.slice(8, 24);

var testDecipher = crypto.createDecipheriv(algorithm, key, iv);
testDecipher.setAutoPadding(false);

describe('Body', function() {
  describe('#constructor', function() {
    it('takes a cipher', function() {
      var bodyBuffer = new Body(testDecipher);

      (typeof bodyBuffer.cipher).should.equal('object');
    });
  });
  describe('$parseKvps', function() {
    it('takes a buffer and returns an array of kvps', function() {
      var body = new Body(testDecipher);

      var kvps = body.parseKvps(testFile);

      kvps.length.should.equal(5);
    });
  });
});
Пример #11
0
  User.prototype.checklogin = function(cookie, req, callback) {
    if (req.query && req.query.cookies) {
      var _cookies = req.query.cookies;
      var arrcookie = _cookies.split(';');
      var _cookie = {};
      for (var i = 0; i < arrcookie.length; i++) {
        var se = arrcookie[i].split('=');
        if (se.length === 2) {
          var sname = string.trim(se[0]);
          if (sname) {
            _cookie[sname] = unescape(se[1]);
          }
        }
      }
      cookie = _cookie;
    }
    var usercookie = cookie[config.COOKIE_PREFIX + 'user'];
    if (usercookie && (usercookie.length % 8) === 0) {

      var key = new Buffer(config.COOKIE_DES_KEY, 'hex');
      var iv = new Buffer(config.COOKIE_DES_IV, 'hex');
      var decipher = crypto.createDecipheriv("des", key, iv);
      decipher.setAutoPadding(false);
      var d;
      try {
        d = decipher.update(usercookie, 'hex', 'binary');
        d += decipher.final('binary');
      } catch (e) {
        callback(false);
      }
      
      if (!d) {
        callback(false);
      }

      var cookieData = d.split("\n");
      if (cookieData.length !== 3) {
        callback(false);
      }

      var cookietime = parseInt(cookieData[0]);
      var account_id = cookieData[1];
      var cookiekey = cookieData[2];
      
      if (cookietime && account_id && cookiekey && (this.core.TIMESTAMP - (cookietime * 1000)) < max_online_time) {
        var that = this;

        var user_page_id = cookie[config.COOKIE_PREFIX + 'page_id'];

        var eventms = ['login', 'user_page_manager', 'manager_default_page'];
        var epm = EventProxy.create(eventms, function (login, userPageManagers, ManagerPages) {
          if (userPageManagers) {
            //获得默认的头像和封面
            for (var i = 0; i < userPageManagers.length; i++) {
              for (var j = 0; j < ManagerPages.length; j++) {
                if (userPageManagers[i].uid == ManagerPages[j].account_id) {
                  if (ManagerPages[j].front_cover_url) {
                    userPageManagers[i].front_cover_url = ManagerPages[j].front_cover_url;
                  }
                  if (ManagerPages[j].avatar_url) {
                    userPageManagers[i].avatar_url = ManagerPages[j].avatar_url;
                  }
                }
                break;
              }
              //password removed
            }
            that.page_manager = userPageManagers;
          }
          callback(login.is_login);
        });

        var events = ['user', 'user_page_relation', 'user_page'];
        var ep = EventProxy.create(events, function (user, userPageRelation, userPages) {
          var is_login = false;
          if (user) {
            is_login = true;

            that.account = user;
            that.accounttype = parseInt(user.accounttype);

            that.showname = user.name;
            that.uid = user.uid;
            that.csrf = that.getusercsrf(cookiekey);
            
            var page;
            if (userPages.length > 0) {
              for (var i = 0; i < userPages.length; i++) {
                for (var j = 0; j < userPageRelation.length; j++) {
                  if (userPages[i]._id.toString() == userPageRelation[j].page_id.toString()) {
                    userPages[i].power = userPageRelation[j].power;
                    userPages[i].uid = userPageRelation[j].account_id;
                  }
                }
              }
              
              that.page_list = userPages;
              if (that.isPageAccessible(user_page_id)) {
                for (var i = 0; i < userPages.length; i++) {
                  if (userPages[i]._id.toString() == user_page_id) {
                    page = userPages[i];
                    break;
                  }
                }
                if (!page) {
                  page = userPages[0];
                }
              } else {
                page = userPages[0];
              }
            } else {
              // no pages
              that.page_list = [];
            }

            if (page) {
              that.page_id = page._id.toString();
              that.page = page;

              that.getNotification(ep.done('notification_count'));

              if (page.name) {
                that.showname = page.name;
              }
              if (page.noaccount) {
                that.inpage = true;
              }
              if (page.power >= 2) {
                that.is_page_manger = true;
              }
            }

            ep.emit('user_current_page', page);
            is_login = true;
          } else {
            epm.emit('user_page_manager', null);
            epm.emit('manager_default_page', null);
          }

          epm.emit('login', { is_login: is_login });
        });

        ep.fail('error', function (err) {
          epm.unbind();
          callback(false);
        });

        epm.fail(function () {
          callback(false);
        });

        ep.all('user_current_page', 'notification_count', function (page) {
          if (page && page.noaccount && page.power >= 3) {
            //inpage
            UserPageRelationProxy.getRelationsByPageId(page._id, function (err, r) {
              var account_ids = [];
              for (var i = 0; i < r.length; i++) {
                /* if (user.uid != r[i].account_id) */ {
                  account_ids.push(r[i].account_id);
                }
              }
              if (account_ids.length > 0) {
                UserAccountProxy.getUsersByIds(account_ids, epm.done('user_page_manager'), true);
                UserPageProxy.getDefaultPages(account_ids, epm.done('manager_default_page'));
              } else {
                epm.emit('user_page_manager', null);
                epm.emit('manager_default_page', null);
              }
            });
          } else {
            epm.emit('user_page_manager', null);
            epm.emit('manager_default_page', null);
          }
        });

        UserPageRelationProxy.getPages(account_id, function (err, userPageRelation) {
          if (err) {
            return ep.emit('error', err);
          }
          ep.emit('user_page_relation', userPageRelation);

          var page_ids = [];
          for (var i = 0; i < userPageRelation.length; i++) {
            page_ids.push(userPageRelation[i].page_id);
          }

          if (page_ids.length > 0) {
            UserPageProxy.getUsersByIds(page_ids, ep.done('user_page'));
          } else {
            ep.emit('user_page', []);
          }
        });

        UserAccountProxy.getUserById(account_id, ep.done('user'));
      } else {
        callback(false);
      }
    } else {
      callback(false);
    }
  };
Пример #12
0
function decryptAESecb(dataBuffer, key, iv) {
	var decipher = crypto.createDecipheriv('aes-128-ecb', key, iv);
	return Buffer.concat([decipher.update(dataBuffer), decipher.final()]).toString();
}
Пример #13
0
function decrypt(text) {
    var iv=text.substr(0,16);
    var cipher = crypto.createDecipheriv(cryptype,secretKey,iv);
    return cipher.update(text.substr(16),dataType,'utf8') + cipher.final('utf8');
}
Пример #14
0
  const key = createSecretKey(keybuf);
  assert.strictEqual(key.type, 'secret');
  assert.strictEqual(key.symmetricKeySize, 32);
  assert.strictEqual(key.asymmetricKeyType, undefined);

  const exportedKey = key.export();
  assert(keybuf.equals(exportedKey));

  const plaintext = Buffer.from('Hello world', 'utf8');

  const cipher = createCipheriv('aes-256-ecb', key, null);
  const ciphertext = Buffer.concat([
    cipher.update(plaintext), cipher.final()
  ]);

  const decipher = createDecipheriv('aes-256-ecb', key, null);
  const deciphered = Buffer.concat([
    decipher.update(ciphertext), decipher.final()
  ]);

  assert(plaintext.equals(deciphered));
}

{
  // Passing an existing key object should throw.
  const publicKey = createPublicKey(publicPem);
  common.expectsError(() => createPublicKey(publicKey), {
    type: TypeError,
    code: 'ERR_INVALID_ARG_TYPE',
    message: 'The "key" argument must be one of type string, Buffer, ' +
             'TypedArray, or DataView. Received type object'
Пример #15
0
 assert.throws(() => {
   crypto.createDecipheriv(`aes-256-${mode}`,
                           'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8',
                           'qkuZpJWCewa6S');
 }, {
 () => crypto.createDecipheriv('des-ede3-cbc', null),
/*
 * For reading we support both PKCS#1 and PKCS#8. If we find a private key,
 * we just take the public component of it and use that.
 */
function read(buf, options, forceType) {
	var input = buf;
	if (typeof (buf) !== 'string') {
		assert.buffer(buf, 'buf');
		buf = buf.toString('ascii');
	}

	var lines = buf.trim().split('\n');

	var m = lines[0].match(/*JSSTYLED*/
	    /[-]+[ ]*BEGIN ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
	assert.ok(m, 'invalid PEM header');

	var m2 = lines[lines.length - 1].match(/*JSSTYLED*/
	    /[-]+[ ]*END ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
	assert.ok(m2, 'invalid PEM footer');

	/* Begin and end banners must match key type */
	assert.equal(m[2], m2[2]);
	var type = m[2].toLowerCase();

	var alg;
	if (m[1]) {
		/* They also must match algorithms, if given */
		assert.equal(m[1], m2[1], 'PEM header and footer mismatch');
		alg = m[1].trim();
	}

	var headers = {};
	while (true) {
		lines = lines.slice(1);
		m = lines[0].match(/*JSSTYLED*/
		    /^([A-Za-z0-9-]+): (.+)$/);
		if (!m)
			break;
		headers[m[1].toLowerCase()] = m[2];
	}

	var cipher, key, iv;
	if (headers['proc-type']) {
		var parts = headers['proc-type'].split(',');
		if (parts[0] === '4' && parts[1] === 'ENCRYPTED') {
			if (typeof (options.passphrase) === 'string') {
				options.passphrase = new Buffer(
				    options.passphrase, 'utf-8');
			}
			if (!Buffer.isBuffer(options.passphrase)) {
				throw (new errors.KeyEncryptedError(
				    options.filename, 'PEM'));
			} else {
				parts = headers['dek-info'].split(',');
				assert.ok(parts.length === 2);
				cipher = parts[0].toLowerCase();
				iv = new Buffer(parts[1], 'hex');
				key = utils.opensslKeyDeriv(cipher, iv,
				    options.passphrase, 1).key;
			}
		}
	}

	/* Chop off the first and last lines */
	lines = lines.slice(0, -1).join('');
	buf = new Buffer(lines, 'base64');

	if (cipher && key && iv) {
		var cipherStream = crypto.createDecipheriv(cipher, key, iv);
		var chunk, chunks = [];
		cipherStream.once('error', function (e) {
			if (e.toString().indexOf('bad decrypt') !== -1) {
				throw (new Error('Incorrect passphrase ' +
				    'supplied, could not decrypt key'));
			}
			throw (e);
		});
		cipherStream.write(buf);
		cipherStream.end();
		while ((chunk = cipherStream.read()) !== null)
			chunks.push(chunk);
		buf = Buffer.concat(chunks);
	}

	/* The new OpenSSH internal format abuses PEM headers */
	if (alg && alg.toLowerCase() === 'openssh')
		return (sshpriv.readSSHPrivate(type, buf));
	if (alg && alg.toLowerCase() === 'ssh2')
		return (rfc4253.readType(type, buf));

	var der = new asn1.BerReader(buf);
	der.originalInput = input;

	/*
	 * All of the PEM file types start with a sequence tag, so chop it
	 * off here
	 */
	der.readSequence();

	/* PKCS#1 type keys name an algorithm in the banner explicitly */
	if (alg) {
		if (forceType)
			assert.strictEqual(forceType, 'pkcs1');
		return (pkcs1.readPkcs1(alg, type, der));
	} else {
		if (forceType)
			assert.strictEqual(forceType, 'pkcs8');
		return (pkcs8.readPkcs8(alg, type, der));
	}
}
 () => crypto.createDecipheriv('des-ede3-cbc', key, 10),
Пример #19
0
Файл: aes.js Проект: yurow/nodex
		this.decode = function(data){
			var deCipher = crypto.createDecipheriv(config.algorithm, 
					config.secretKey,config.iv);
			return deCipher.update(data, config.crypto, config.encoding) 
					+ cipher.final(config.encoding);
		};
Пример #20
0
 elements.createCipher = function(password) {
     var key = createPkcs12Info(password, salt, 24, iterations, 1);
     var iv = createPkcs12Info(password, salt, 8, iterations, 2);
     return crypto.createDecipheriv('des-ede3-cbc', key.toString('binary'), iv.toString('binary'));
 };
var crypto = require('crypto'),
	// Fun quirk. We have to specify a IV even if ECB is not using IV at all.
	// CreateCipher uses a password from which the key is derived 
	// (the IV is derived as well, but that is ignored for ECB). The createCipheriv method however directly uses a key as bytes
    iv = new Buffer(''),
    // 32 * 8 Char = 256 bytes for the key
    key = new Buffer('e6ee5c9847445e126008575068f1c4429ad34dbfcf7c675f6459c9a71919c0bc', 'hex'),
    cipher = crypto.createCipheriv('aes-256-ecb', key, iv),
    decipher = crypto.createDecipheriv('aes-256-ecb', key, iv);

cipher.setAutoPadding(true);
var toEncrypt = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.";
var encryptedString = cipher.update( new Buffer(toEncrypt, 'utf8'),'buffer', 'hex');
encryptedString += cipher.final('hex');
console.log(toEncrypt,encryptedString);

decipher.setAutoPadding(false);
var decryptedString = decipher.update( encryptedString,'hex', 'buffer');
decryptedString += decipher.final('hex');
console.log(encryptedString,decryptedString);
Пример #22
0
  setTimeout(function(){
    
    var sec_key = message_ori.userpost.dm.key;
    var sec_body = message_ori.userpost.dm.body;
    var sec_mac = message_ori.userpost.dm.mac;
    var sec_orig = message_ori.userpost.dm.orig;

    if (!Buffer.isBuffer(sec_key)) {
        sec_key = new Buffer(sec_key, "hex");
    }
    if (!Buffer.isBuffer(sec_body)) {
        sec_body = new Buffer(sec_body, "hex");
    }
    if (!Buffer.isBuffer(sec_mac)) {
        sec_mac = new Buffer(sec_mac, "hex");
    }

    var pubkey = Bitcoin.ECPair.fromPublicKeyBuffer(sec_key)
    var secret = pubkey.Q.multiply(thisResource._btcKey.d).getEncoded().slice(1,33)

    var hash_secret = Crypto.createHash('sha512').update(secret).digest()
    var aes_key = hash_secret.slice(0,32)

    var hmac_key = hash_secret.slice(32,64)

    var hmac=Crypto.createHmac("sha512",hmac_key)
    hmac.update(sec_body)
    var hmac_val = hmac.digest()

    if(sec_mac.toString()!=hmac_val.toString()){

      thisResource._handleError({
        message: "Post could not be decrypted.",
        code: 32063
      })

    }else{

      try{
        // note: new Buffer(16) does not give an empty (all zero) buffer
        var iv = new Buffer("00000000000000000000000000000000","hex");
        var decrypter = Crypto.createDecipheriv("aes-256-cbc",aes_key,iv)
        decrypter.setAutoPadding()
        var out = [];
        out.push(decrypter.update(sec_body))
        out.push(decrypter.final())
        var decrypted = bencode.decode(Buffer.concat(out).slice(0,sec_orig));

        for(var key in decrypted){
          if(Buffer.isBuffer(decrypted[key])){
            decrypted[key] = decrypted[key].toString();
          }
        }

        cbfunc(decrypted)

      }catch(e){
        thisResource._handleError({
          message: "Post could not be decrypted",
          code: 32063
        })
      }
    }
    
  },0)
Пример #23
0
 decrypt: function(code) {
   var decipher = crypto.createDecipheriv(encryptionType, key(), '');
   decipher.end(new Buffer(code, 'hex'));
   return decipher.read().toString();
 }
Пример #24
0
      assert.strictEqual(hex, test.ct);
      assert.strictEqual(auth_tag.toString('hex'), test.tag);
    }
  }

  {
    if (isCCM && common.hasFipsCrypto) {
      assert.throws(() => {
        crypto.createDecipheriv(test.algo,
                                Buffer.from(test.key, 'hex'),
                                Buffer.from(test.iv, 'hex'),
                                options);
      }, errMessages.FIPS);
    } else {
      const decrypt = crypto.createDecipheriv(test.algo,
                                              Buffer.from(test.key, 'hex'),
                                              Buffer.from(test.iv, 'hex'),
                                              options);
      decrypt.setAuthTag(Buffer.from(test.tag, 'hex'));
      if (test.aad)
        decrypt.setAAD(Buffer.from(test.aad, 'hex'), aadOptions);

      const outputEncoding = test.plainIsHex ? 'hex' : 'ascii';

      let msg = decrypt.update(test.ct, 'hex', outputEncoding);
      if (!test.tampered) {
        msg += decrypt.final(outputEncoding);
        assert.strictEqual(msg, test.plain);
      } else {
        // Assert that final throws if input data could not be verified!
        assert.throws(function() { decrypt.final('hex'); }, errMessages.auth);
      }
Пример #25
0
assert.deepStrictEqual(dh1.getPrime(), dh4.getPrime());
assert.deepStrictEqual(dh1.getGenerator(), dh4.getGenerator());
assert.deepStrictEqual(dh1.getPrivateKey(), dh4.getPrivateKey());
assert.strictEqual(dh4.verifyError, 0);

const secret4 = dh4.computeSecret(key2, 'hex', 'base64');

assert.strictEqual(secret1, secret4);

const wrongBlockLength =
  /^Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length$/;

// Run this one twice to make sure that the dh3 clears its error properly
{
  const c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), '');
  assert.throws(() => {
    c.final('utf8');
  }, wrongBlockLength);
}

{
  const c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), '');
  assert.throws(() => {
    c.final('utf8');
  }, wrongBlockLength);
}

assert.throws(() => {
  dh3.computeSecret('');
}, /^Error: Supplied key is too small$/);
Пример #26
0
 assert.throws(() => {
   crypto.createDecipheriv(test.algo,
                           Buffer.from(test.key, 'hex'),
                           Buffer.from(test.iv, 'hex'),
                           options);
 }, errMessages.FIPS);
 function decrypt(val, pad) {
       var c = crypto.createDecipheriv('aes256', key, iv);
       c.setAutoPadding(pad);
       return c.update(val, 'binary') + c[decipherFinal]('utf8');
 }
Пример #28
0
 common.expectsError(() => {
   const decrypt = crypto.createDecipheriv('aes-128-gcm',
                                           'FxLKsqdmv0E9xrQh',
                                           'qkuZpJWCewa6Szih');
   decrypt.setAuthTag(Buffer.from('1'.repeat(length)));
 }, {
Пример #29
0
    return function (req, res, next) {
        res.set('Cache-Control', 'no-cache');

        logger.info({ user: req.user ? req.user._json : undefined }, 'sharelock access request');

        if (req.user && req.user.provider !== 'twitter' && !req.user._json.email_verified) {
            return res.render('invalid', { details: 'Your e-mail has not been verified'});
        }

        var request_keys;
        try {
            request_keys = ensure_key(req.params[0]);
        }
        catch (e) {
            return res.render('invalid', { details: 'For security reasons this sharelock is no longer supported.'});
        }

        var resource = req.params[1].replace(/\//g, '');
        var tokens = resource.split('.');
        if (tokens.length !== 3 || tokens[0].length === 0 || tokens[1].length === 0 || tokens[2].length === 0)
            return res.render('invalid', { details: 'The URL is malformed and cannot be processed.'});

        try {
            tokens[0] = base64url.toBase64(tokens[0]); // signature
            tokens[1] = new Buffer(base64url.toBase64(tokens[1]), 'base64'); // encrypted data
            tokens[2] = new Buffer(base64url.toBase64(tokens[2]), 'base64'); // iv
            var signature = crypto.createHmac('sha256', request_keys.signature_key).update(tokens[1]).update(tokens[2]).digest('base64');
            if (!cryptiles.fixedTimeComparison(signature, tokens[0]))
                throw null;
        }
        catch (e) {
            return res.render('invalid', { details: 'Signature verification failed: the data could have been tampered with.'});
        }

        try {
            var cipher = crypto.createDecipheriv('aes-256-ctr', request_keys.encryption_key, tokens[2]);
            var plaintext = cipher.update(tokens[1], 'base64', 'utf8') + cipher.final('utf8');
            resource = JSON.parse(plaintext);
            if (!resource || typeof resource !== 'object' || typeof resource.d !== 'string'
                || !Array.isArray(resource.a))
                throw null;
        }
        catch (e) {
            return res.render('invalid', { details: 'Encrypted data is malformed.' });
        }

        var allowed;
        var email = get_email(req.user);
        var twitter;
        var email_domains = {};
        for (var i in resource.a) {
            var acl = resource.a[i];
            if (acl.k === 'g') {
                if (email && normalize_gmail(email) === acl.v) {
                    allowed = true;
                } else {
                    email_domains[acl.v.substring(acl.v.indexOf('@'))] = 1;
                }
            }
            else if (acl.k === 'e') {
                if (email === acl.v) {
                    allowed = true;
                }
                else {
                    email_domains[acl.v.substring(acl.v.indexOf('@'))] = 1;
                }
            }
            else if (acl.k === 'd') {
                if (email && email.indexOf(acl.v, email.length - acl.v.length) !== -1) {
                    allowed = true;
                }
                else {
                    email_domains[acl.v] = 1;
                }
            }
            else if (acl.k === 't') {
                if (req.user && req.user.provider === 'twitter' && req.user._json.screen_name.toLowerCase() === acl.v) {
                    allowed = true;
                }
                else {
                    twitter = true;
                }
            }

            if (allowed) break;
        }

        if (allowed) {
            var model = {
                data: resource.d,
                user: req.user,
                provider: provider_friendly_name[req.user.provider] || req.user.provider,
                logout_url: '/logout'
            };
            res.render('data', model);
        }
        else {
            email_domains = Object.getOwnPropertyNames(email_domains);
            var model = {
                auth0_client_id: process.env.AUTH0_CLIENT_ID,
                auth0_domain: process.env.AUTH0_DOMAIN,
                auth0_callback: process.env.AUTH0_CALLBACK,
                user: req.user,
                email: req.user ? get_email(req.user) : undefined,
                providers: get_provider_config(twitter, email_domains, req.user ? req.user.provider : undefined),
                allow_twitter: twitter,
                allow_domains: email_domains,
                provider: req.user ? (provider_friendly_name[req.user.provider] || req.user.provider) : undefined,
                logout_url: '/logout?r=' + req.originalUrl,
                provider_friendly_name: provider_friendly_name
            };

            req.session.bookmark = req.originalUrl;
            res.render('login', model);
        }
    };
Пример #30
0
var createDecipher= function(key, iv) {
  return crypto.createDecipheriv('aes-192-cfb8', key, iv);
};