Пример #1
0
	function encrypt(data){
		var options = {
			key: pri.key,
			padding: constants.RSA_PKCS1_PADDING
		}
		var source = new Buffer(_base64encode(data));
		var encrypted = new Buffer(0);

		//分段加密
		var maxSize = _get_MAX_ENCRYPT_BLOCK();
		if(source.length > maxSize){
			var count = Math.ceil(source.length * 1.0 / maxSize);

			for(var i=0; i<count; i++){
				var bufferSize = maxSize;
				if(i+1 >= count){bufferSize = source.length - (i * maxSize)}

				var buffer = new Buffer(bufferSize);
				source.copy(buffer, 0, i * maxSize, (i + 1) * maxSize)
				var bufferEncrypted = crypto.publicEncrypt(options, buffer)
				encrypted = Buffer.concat([encrypted, bufferEncrypted])
			}
		}else{
			encrypted = crypto.publicEncrypt(options, source)
		}
		
		return encrypted.toString('base64');
	}
Пример #2
0
function test_rsa(padding) {
  const size = (padding === 'RSA_NO_PADDING') ? 1024 / 8 : 32;
  const input = Buffer.allocUnsafe(size);
  for (let i = 0; i < input.length; i++)
    input[i] = (i * 7 + 11) & 0xff;
  const bufferToEncrypt = Buffer.from(input);

  padding = constants[padding];

  const encryptedBuffer = crypto.publicEncrypt({
    key: rsaPubPem,
    padding: padding
  }, bufferToEncrypt);

  let decryptedBuffer = crypto.privateDecrypt({
    key: rsaKeyPem,
    padding: padding
  }, encryptedBuffer);
  assert.deepStrictEqual(decryptedBuffer, input);

  decryptedBuffer = crypto.privateDecrypt({
    key: rsaPkcs8KeyPem,
    padding: padding
  }, encryptedBuffer);
  assert.deepStrictEqual(decryptedBuffer, input);
}
Пример #3
0
// publicEncrypt and  privateDecrypt only work with
// small buffer that depends of the key size.
function publicEncrypt_native(buffer, public_key) {
    assert(buffer instanceof Buffer, "Expecting a buffer");
    return crypto.publicEncrypt({
       key: public_key,
       padding:  constants.RSA_PKCS1_PADDING
    }, buffer);
}
Пример #4
0
// Tests that a key pair can be used for encryption / decryption.
function testEncryptDecrypt(publicKey, privateKey) {
  const message = 'Hello Node.js world!';
  const plaintext = Buffer.from(message, 'utf8');
  const ciphertext = publicEncrypt(publicKey, plaintext);
  const received = privateDecrypt(privateKey, ciphertext);
  assert.strictEqual(received.toString('utf8'), message);
}
Пример #5
0
 var encryptStringWithRsaPublicKey = function (toEncrypt, relativeOrAbsolutePathToPublicKey) {
   var absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey)
   var publicKey = fs.readFileSync(absolutePath, 'utf8')
   var buffer = new Buffer(toEncrypt)
   var encrypted = crypto.publicEncrypt(publicKey, buffer)
   return encrypted.toString('base64')
 }
Пример #6
0
exports.generateSessionKey = function() {
  var sessionKey = crypto.randomBytes(32);
  var cryptedSessionKey = crypto.publicEncrypt(publicKey, sessionKey);
  return {
    plain: sessionKey,
    encrypted: cryptedSessionKey
  };
};
Пример #7
0
 t.test('node encrypt, we decrypt', function (t) {
   t.plan(1);
   var data = new Buffer('node encrypt, we decrypt');
   var encrypted = crypto.publicEncrypt(pemKeys.public, data);
   rsa.decrypt(jwkKeys.private, encrypted).then(function (decrypt) {
     t.equals(decrypt.toString(), 'node encrypt, we decrypt');
   }).catch(function (e) {
     t.error(e||'error');
   });
 });
Пример #8
0
exports.publicEncrypt = function(public_str, data) {
    if ('string' === typeof data) {
        // console.log('原来的数据为:');
        // console.log(data);
        data = Buffer.from(data, 'utf8');
        // console.log('现在的数据为:');
        // console.log(data);
    }

    return crypto.publicEncrypt(public_str, data);
};
Пример #9
0
//xx console.log("xxxxxxxxxxxx exports.RSA_PKCS1_PADDING",exports.RSA_PKCS1_PADDING,ursa.RSA_PKCS1_PADDING,constants.RSA_PKCS1_PADDING);
//xx console.log("xxxxxxxxxxxx exports.RSA_PKCS1_OAEP_PADDING",exports.RSA_PKCS1_OAEP_PADDING,ursa.RSA_PKCS1_OAEP_PADDING,constants.RSA_PKCS1_OAEP_PADDING);

// publicEncrypt and  privateDecrypt only work with
// small buffer that depends of the key size.
function publicEncrypt_native(buffer, public_key, algorithm) {

    algorithm = algorithm || crypto_utils.RSA_PKCS1_PADDING;
    assert(algorithm === crypto_utils.RSA_PKCS1_PADDING || algorithm === crypto_utils.RSA_PKCS1_OAEP_PADDING);
    assert(buffer instanceof Buffer, "Expecting a buffer");

    return crypto.publicEncrypt({
        key: public_key,
        padding: algorithm
    }, buffer);
}
Пример #10
0
        encrypt: function (buffer, usePrivate) {
            if (usePrivate) {
                return jsEngine.encrypt(buffer, usePrivate);
            }
            var padding = constants.RSA_PKCS1_OAEP_PADDING;
            if (options.encryptionScheme === 'pkcs1') {
                padding = constants.RSA_PKCS1_PADDING;
            }

            return crypto.publicEncrypt({
                key: options.rsaUtils.exportKey('public'),
                padding: padding
            }, buffer);
        },
Пример #11
0
socket.on('message', function (data) {
  var incomingMessage = JSON.parse(data.toString('utf8'));
  switch (incomingMessage.code) {
  case 100:
    //获取服务器公钥
    RSAPubKey = new Buffer(incomingMessage.RSAPubKey, 'base64').toString('utf8');
    //获取客户端ECDH的PublicKey
    var ECDHClientPublicKey = ecdh.getPublicKey();
    //将客户端的ECDHClientPublicKey用RSA公钥加密
    socket.send(JSON.stringify({ code: 101, PublicKey: crypto.publicEncrypt(RSAPubKey, ECDHClientPublicKey).toString('base64'), timestamp: new Date().getTime() }));
    console.log(colors.green("Sended ECDHClientPublicKey: ") + ECDHClientPublicKey.toString('base64'));
    break;
  case 101:
    //解密服务器ECDH的PublicKey
    var ECDHServerPublicKey = crypto.publicDecrypt(RSAPubKey, new Buffer(incomingMessage.PublicKey, 'base64')).toString("base64");
    console.log(colors.green('Recive a ECDHServerPublicKey from server: ') + ECDHServerPublicKey);
    DESKEY = ecdh.computeSecret(ECDHServerPublicKey, 'base64', 'base64'); //获取DESKEY
    console.log(colors.green('Generator DESKEY: ') + DESKEY);
    socket.send(DESCrypto.Cipher({ code: 10, msg: "hello server", DESKEY: DESKEY }, DESKEY));
    break;
  case 102:
    var MessageDecipher = DESCrypto.Decipher(incomingMessage.data, DESKEY);
    var hash = MessageDecipher[1].hash;
    var data = MessageDecipher[0];
    if (crypto.createHash('sha512').update(JSON.stringify(data)).digest('base64') == hash) {
      console.log(colors.green("Verify hash success."));
      if (data.DESKEY == DESKEY) {
        console.log(colors.green("Verify DESKEY success."));
        switch (data.code) {
        case 10:
          console.log(colors.green("MSG from server: ") + data.msg);
          // socket.send(MessageCipherfun({ code: 10, msg: "hello server", DESKEY: DESKEY }));
          break;
        }
      } else {
        console.log(colors.green("Verify DESKEY success."));
      }
    } else {
      console.log(colors.green("Verify hash success."));
    }
    break;
  }
});
Пример #12
0
ClientHandshakeHandler.prototype.send_keyExchange = function() {

    log.info( 'Constructing key exchange' );

    var publicKey = Certificate.getPublicKeyPem( this.certificate );
    var exchangeKeys = crypto.publicEncrypt({
            key: publicKey,
            padding: constants.RSA_PKCS1_PADDING
        }, this.newParameters.preMasterKey );

    var keyExchange = new DtlsClientKeyExchange_rsa({
        exchangeKeys: exchangeKeys
    });
    var keyExchangeHandshake = this.handshakeBuilder.createHandshakes(
            keyExchange ).getBuffer();

    this.newParameters.digestHandshake( keyExchangeHandshake );
    this.newParameters.preMasterKey = null;

    var changeCipherSpec = new DtlsChangeCipherSpec({ value: 1 });

    var prf_func = prf( this.version );
    var verifyData = prf_func(
        this.newParameters.masterKey,
        "client finished",
        this.newParameters.getHandshakeDigest(),
        12
    );
    var finished = new DtlsFinished({ verifyData: verifyData });
    var finishedHandshake = this.handshakeBuilder.createHandshakes(
            finished ).getBuffer();
    this.newParameters.digestHandshake( finishedHandshake );

    var keyExchangeFragments = this.handshakeBuilder.fragmentHandshakes( keyExchangeHandshake );
    var finishedFragments = this.handshakeBuilder.fragmentHandshakes( finishedHandshake );

    var outgoingFragments = keyExchangeFragments;
    outgoingFragments.push( changeCipherSpec );
    outgoingFragments = outgoingFragments.concat( finishedFragments );

    this.setResponse( outgoingFragments );
};
Пример #13
0
module.exports = function(login, password) {
	var data = Buffer.from(login + '\u0000' + password);
	var publicKey = Buffer.from(GOOGLE_DEFAULT_PUBLIC_KEY, 'base64');
	var hash = crypto.createHash('sha1');
	var rsaPem = decompose(publicKey);

	var sha1 = hash.update(publicKey);
	var digest = sha1.digest();
	var signature = Buffer.concat([
		Buffer.from('\x00'),
		digest.slice(0, 4)
	]);

	var encrypted = crypto.publicEncrypt(rsaPem, data);

	var res = Buffer.concat([
		signature,
		encrypted
	]);

	return base64EncodeUrlSafe(res);
}
Пример #14
0
        encrypt: function (buffer, usePrivate) {
            if (usePrivate) {
                return jsEngine.encrypt(buffer, usePrivate);
            }
            var padding = constants.RSA_PKCS1_OAEP_PADDING;
            if (options.encryptionScheme === 'pkcs1') {
                padding = constants.RSA_PKCS1_PADDING;
            }
            if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) {
                padding = options.encryptionSchemeOptions.padding;
            }

            var data = buffer;
            if (padding === constants.RSA_NO_PADDING) {
                data = pkcs1Scheme.pkcs0pad(buffer);
            }

            return crypto.publicEncrypt({
                key: options.rsaUtils.exportKey('public'),
                padding: padding
            }, data);
        },
Пример #15
0
/*
 * Encrypt the username/password for use in `EncryptedPasswd`.
 * refs:
 * - https://github.com/yeriomin/play-store-api/blob/master/src/main/java/com/github/yeriomin/playstoreapi/PasswordEncrypter.java
 * - https://github.com/subtletech/google_play_store_password_encrypter/blob/master/google_play_store_password_encrypter.rb
 *
 *  We first convert the public key to RSA PEM format which is used
 *  throughout node's standard library.
 *
 *  The result is something like the below
 *  -----------------------------------------------------------------------------
 *  |00|4 bytes of sha1(publicKey)|rsaEncrypt(publicKeyPem, "login\x00password")|
 *  -----------------------------------------------------------------------------
 *  The result is then base64 URL-safe encoded and can be used as the
 *  `EncryptedPasswd`
 *  @param {String} login - Google username.
 *  @param {String} password - Google password.
 *  @return {String} `EncryptedPasswd` value.
 */
function encryptLoginSync (login, password) {
  const data = Buffer.from(login + '\u0000' + password);
  const publicKey = Buffer.from(GOOGLE_DEFAULT_PUBLIC_KEY, 'base64');
  const hash = crypto.createHash('sha1');
  const rsaPem = decompose(publicKey);

  const sha1 = hash.update(publicKey);
  const digest = sha1.digest();
  const signature = Buffer.concat([
    Buffer.from('\x00'),
    digest.slice(0, 4)
  ]);

  const encrypted = crypto.publicEncrypt(rsaPem, data);

  const res = Buffer.concat([
    signature,
    encrypted
  ]);

  return base64EncodeUrlSafe(res);
}
Пример #16
0
 assert.throws(() => {
   crypto.publicEncrypt({
     key: rsaKeyPemEncrypted,
     passphrase: 'wrong'
   }, encryptedBuffer);
 }, decryptError);
Пример #17
0
const rsaKeyPemEncrypted = fs.readFileSync(
  `${fixtDir}/test_rsa_privkey_encrypted.pem`, 'ascii');
const dsaPubPem = fs.readFileSync(`${fixtDir}/test_dsa_pubkey.pem`, 'ascii');
const dsaKeyPem = fs.readFileSync(`${fixtDir}/test_dsa_privkey.pem`, 'ascii');
const dsaKeyPemEncrypted = fs.readFileSync(
  `${fixtDir}/test_dsa_privkey_encrypted.pem`, 'ascii');

const decryptError =
  /^Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt$/;

// Test RSA encryption/decryption
{
  const input = 'I AM THE WALRUS';
  const bufferToEncrypt = Buffer.from(input);

  let encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt);

  let decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer);
  assert.strictEqual(decryptedBuffer.toString(), input);

  let decryptedBufferWithPassword = crypto.privateDecrypt({
    key: rsaKeyPemEncrypted,
    passphrase: 'password'
  }, encryptedBuffer);
  assert.strictEqual(decryptedBufferWithPassword.toString(), input);

  encryptedBuffer = crypto.publicEncrypt({
    key: rsaKeyPemEncrypted,
    passphrase: 'password'
  }, bufferToEncrypt);
Пример #18
0
 iterateObj(customerData, function (value, key) {
   return isEncrypted(value, key)
     ? crypto.publicEncrypt(publicKey, new Buffer(value, 'utf-8')).toString('base64')
     : value;
 });
Пример #19
0
  const publicDER = publicKey.export({
    format: 'der',
    type: 'pkcs1'
  });

  const privateDER = privateKey.export({
    format: 'der',
    type: 'pkcs1'
  });

  assert(Buffer.isBuffer(publicDER));
  assert(Buffer.isBuffer(privateDER));

  const plaintext = Buffer.from('Hello world', 'utf8');
  const ciphertexts = [
    publicEncrypt(publicKey, plaintext),
    publicEncrypt({ key: publicKey }, plaintext),
    // Test distinguishing PKCS#1 public and private keys based on the
    // DER-encoded data only.
    publicEncrypt({ format: 'der', type: 'pkcs1', key: publicDER }, plaintext),
    publicEncrypt({ format: 'der', type: 'pkcs1', key: privateDER }, plaintext)
  ];

  const decryptionKeys = [
    privateKey,
    { format: 'pem', key: privatePem },
    { format: 'der', type: 'pkcs1', key: privateDER }
  ];

  for (const ciphertext of ciphertexts) {
    for (const key of decryptionKeys) {
Пример #20
0
    Crypt.prototype.encrypt = function (data, iv, f)
    {
        "use strict";

        var key, ekey, iv64, cipher, jdata, edata = [];

        try
        {
            if (!f)
            {
                f = iv;
                iv = null;
            }

            if (this.key.is_public)
            {
                key = crypto.randomBytes(Crypt._AES_128_KEY_SIZE);

                ekey = crypto.publicEncrypt(
                {
                    key: this.key.key,
                    padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
                }, key);

                if (this.encoding)
                {
                    ekey = ekey.toString(this.encoding);
                }
            }
            else if (!this.key.is_private)
            {
                key = this.key.key || this.key;
            }
            else
            {
                throw new Error("can't encrypt using private key");
            }

            iv = iv || crypto.randomBytes(Crypt._AES_BLOCK_SIZE);

            if (typeof iv === 'string')
            {
                iv = new Buffer(iv, 'binary');
            }

            iv64 = this.encoding ? iv.toString(this.encoding) : iv;

            cipher = crypto.createCipheriv('AES-128-CBC', key, iv);
            cipher.setAutoPadding(this.options.pad);

            jdata = this.stringify(data);

            if (this.options.check)
            {
                edata.push(cipher.update(crypto.createHash('sha256')
                                               .update(jdata, 'binary')
                                               .digest(),
                                         undefined,
                                         this.encoding));
            }

            edata.push(cipher.update(jdata, 'binary', this.encoding));
            edata.push(cipher.final(this.encoding));

            if (this.encoding)
            {
                edata = edata.join('');
            }
            else
            {
                edata = Buffer.concat(edata);
            }
        }
        catch (ex)
        {
            return f.call(this, Crypt._ensure_error(ex));
        }

        f.call(this, null, { iv: iv64, data: edata, ekey: ekey, version: Crypt.get_version() });
    };
var crypto = require('crypto')
var fs = require('fs')

var alice_private = fs.readFileSync('./keys/pkey.pem')
var alice_public = fs.readFileSync('./keys/public.pem')

var message = Buffer('This needs to stay secret.')
var encrypted_message = crypto.publicEncrypt(alice_public, message)
var decrypted_message = crypto.privateDecrypt(alice_private, encrypted_message)

console.log(message.toString(), decrypted_message.toString())
Пример #22
0
var crypto = require('crypto');
var buffer = require('buffer');

var dh = crypto.createDiffieHellman(1024);
var publicKey = dh.generateKeys('hex');
var privateKey = dh.getPrivateKey('hex');

// var fs = require('fs');

// var privateKey = fs.readFileSync('./key.pem');
// var publicKey = fs.readFileSync('./cert.pem');

var data = 'Hello World';
var buffer = new Buffer(data, 'utf8');

// 공개키로 암호화
var encrypted = crypto.publicEncrypt(publicKey, buffer);
// console.log(encrypted.toString('hex'));

// 개인키로 복호화
var decrypted = crypto.privateDecrypt(privateKey, encrypted);
console.log('decrypted : ', decrypted.toString());