first commit

This commit is contained in:
jefferyzhao
2025-07-31 17:44:12 +08:00
commit b9bdc8598b
42390 changed files with 4467935 additions and 0 deletions

398
node_modules/node-rsa/src/NodeRSA.js generated vendored Normal file
View File

@ -0,0 +1,398 @@
/*!
* RSA library for Node.js
*
* Author: rzcoder
* License MIT
*/
var constants = require('constants');
var rsa = require('./libs/rsa.js');
var crypt = require('crypto');
var ber = require('asn1').Ber;
var _ = require('./utils')._;
var utils = require('./utils');
var schemes = require('./schemes/schemes.js');
var formats = require('./formats/formats.js');
if (typeof constants.RSA_NO_PADDING === "undefined") {
//patch for node v0.10.x, constants do not defined
constants.RSA_NO_PADDING = 3;
}
module.exports = (function () {
var SUPPORTED_HASH_ALGORITHMS = {
node10: ['md4', 'md5', 'ripemd160', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'],
node: ['md4', 'md5', 'ripemd160', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'],
iojs: ['md4', 'md5', 'ripemd160', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'],
browser: ['md5', 'ripemd160', 'sha1', 'sha256', 'sha512']
};
var DEFAULT_ENCRYPTION_SCHEME = 'pkcs1_oaep';
var DEFAULT_SIGNING_SCHEME = 'pkcs1';
var DEFAULT_EXPORT_FORMAT = 'private';
var EXPORT_FORMAT_ALIASES = {
'private': 'pkcs1-private-pem',
'private-der': 'pkcs1-private-der',
'public': 'pkcs8-public-pem',
'public-der': 'pkcs8-public-der',
};
/**
* @param key {string|buffer|object} Key in PEM format, or data for generate key {b: bits, e: exponent}
* @constructor
*/
function NodeRSA(key, format, options) {
if (!(this instanceof NodeRSA)) {
return new NodeRSA(key, format, options);
}
if (_.isObject(format)) {
options = format;
format = undefined;
}
this.$options = {
signingScheme: DEFAULT_SIGNING_SCHEME,
signingSchemeOptions: {
hash: 'sha256',
saltLength: null
},
encryptionScheme: DEFAULT_ENCRYPTION_SCHEME,
encryptionSchemeOptions: {
hash: 'sha1',
label: null
},
environment: utils.detectEnvironment(),
rsaUtils: this
};
this.keyPair = new rsa.Key();
this.$cache = {};
if (Buffer.isBuffer(key) || _.isString(key)) {
this.importKey(key, format);
} else if (_.isObject(key)) {
this.generateKeyPair(key.b, key.e);
}
this.setOptions(options);
}
/**
* Set and validate options for key instance
* @param options
*/
NodeRSA.prototype.setOptions = function (options) {
options = options || {};
if (options.environment) {
this.$options.environment = options.environment;
}
if (options.signingScheme) {
if (_.isString(options.signingScheme)) {
var signingScheme = options.signingScheme.toLowerCase().split('-');
if (signingScheme.length == 1) {
if (SUPPORTED_HASH_ALGORITHMS.node.indexOf(signingScheme[0]) > -1) {
this.$options.signingSchemeOptions = {
hash: signingScheme[0]
};
this.$options.signingScheme = DEFAULT_SIGNING_SCHEME;
} else {
this.$options.signingScheme = signingScheme[0];
this.$options.signingSchemeOptions = {
hash: null
};
}
} else {
this.$options.signingSchemeOptions = {
hash: signingScheme[1]
};
this.$options.signingScheme = signingScheme[0];
}
} else if (_.isObject(options.signingScheme)) {
this.$options.signingScheme = options.signingScheme.scheme || DEFAULT_SIGNING_SCHEME;
this.$options.signingSchemeOptions = _.omit(options.signingScheme, 'scheme');
}
if (!schemes.isSignature(this.$options.signingScheme)) {
throw Error('Unsupported signing scheme');
}
if (this.$options.signingSchemeOptions.hash &&
SUPPORTED_HASH_ALGORITHMS[this.$options.environment].indexOf(this.$options.signingSchemeOptions.hash) === -1) {
throw Error('Unsupported hashing algorithm for ' + this.$options.environment + ' environment');
}
}
if (options.encryptionScheme) {
if (_.isString(options.encryptionScheme)) {
this.$options.encryptionScheme = options.encryptionScheme.toLowerCase();
this.$options.encryptionSchemeOptions = {};
} else if (_.isObject(options.encryptionScheme)) {
this.$options.encryptionScheme = options.encryptionScheme.scheme || DEFAULT_ENCRYPTION_SCHEME;
this.$options.encryptionSchemeOptions = _.omit(options.encryptionScheme, 'scheme');
}
if (!schemes.isEncryption(this.$options.encryptionScheme)) {
throw Error('Unsupported encryption scheme');
}
if (this.$options.encryptionSchemeOptions.hash &&
SUPPORTED_HASH_ALGORITHMS[this.$options.environment].indexOf(this.$options.encryptionSchemeOptions.hash) === -1) {
throw Error('Unsupported hashing algorithm for ' + this.$options.environment + ' environment');
}
}
this.keyPair.setOptions(this.$options);
};
/**
* Generate private/public keys pair
*
* @param bits {int} length key in bits. Default 2048.
* @param exp {int} public exponent. Default 65537.
* @returns {NodeRSA}
*/
NodeRSA.prototype.generateKeyPair = function (bits, exp) {
bits = bits || 2048;
exp = exp || 65537;
if (bits % 8 !== 0) {
throw Error('Key size must be a multiple of 8.');
}
this.keyPair.generate(bits, exp.toString(16));
this.$cache = {};
return this;
};
/**
* Importing key
* @param keyData {string|buffer|Object}
* @param format {string}
*/
NodeRSA.prototype.importKey = function (keyData, format) {
if (!keyData) {
throw Error("Empty key given");
}
if (format) {
format = EXPORT_FORMAT_ALIASES[format] || format;
}
if (!formats.detectAndImport(this.keyPair, keyData, format) && format === undefined) {
throw Error("Key format must be specified");
}
this.$cache = {};
return this;
};
/**
* Exporting key
* @param [format] {string}
*/
NodeRSA.prototype.exportKey = function (format) {
format = format || DEFAULT_EXPORT_FORMAT;
format = EXPORT_FORMAT_ALIASES[format] || format;
if (!this.$cache[format]) {
this.$cache[format] = formats.detectAndExport(this.keyPair, format);
}
return this.$cache[format];
};
/**
* Check if key pair contains private key
*/
NodeRSA.prototype.isPrivate = function () {
return this.keyPair.isPrivate();
};
/**
* Check if key pair contains public key
* @param [strict] {boolean} - public key only, return false if have private exponent
*/
NodeRSA.prototype.isPublic = function (strict) {
return this.keyPair.isPublic(strict);
};
/**
* Check if key pair doesn't contains any data
*/
NodeRSA.prototype.isEmpty = function (strict) {
return !(this.keyPair.n || this.keyPair.e || this.keyPair.d);
};
/**
* Encrypting data method with public key
*
* @param buffer {string|number|object|array|Buffer} - data for encrypting. Object and array will convert to JSON string.
* @param encoding {string} - optional. Encoding for output result, may be 'buffer', 'binary', 'hex' or 'base64'. Default 'buffer'.
* @param source_encoding {string} - optional. Encoding for given string. Default utf8.
* @returns {string|Buffer}
*/
NodeRSA.prototype.encrypt = function (buffer, encoding, source_encoding) {
return this.$$encryptKey(false, buffer, encoding, source_encoding);
};
/**
* Decrypting data method with private key
*
* @param buffer {Buffer} - buffer for decrypting
* @param encoding - encoding for result string, can also take 'json' or 'buffer' for the automatic conversion of this type
* @returns {Buffer|object|string}
*/
NodeRSA.prototype.decrypt = function (buffer, encoding) {
return this.$$decryptKey(false, buffer, encoding);
};
/**
* Encrypting data method with private key
*
* Parameters same as `encrypt` method
*/
NodeRSA.prototype.encryptPrivate = function (buffer, encoding, source_encoding) {
return this.$$encryptKey(true, buffer, encoding, source_encoding);
};
/**
* Decrypting data method with public key
*
* Parameters same as `decrypt` method
*/
NodeRSA.prototype.decryptPublic = function (buffer, encoding) {
return this.$$decryptKey(true, buffer, encoding);
};
/**
* Encrypting data method with custom key
*/
NodeRSA.prototype.$$encryptKey = function (usePrivate, buffer, encoding, source_encoding) {
try {
var res = this.keyPair.encrypt(this.$getDataForEncrypt(buffer, source_encoding), usePrivate);
if (encoding == 'buffer' || !encoding) {
return res;
} else {
return res.toString(encoding);
}
} catch (e) {
throw Error('Error during encryption. Original error: ' + e);
}
};
/**
* Decrypting data method with custom key
*/
NodeRSA.prototype.$$decryptKey = function (usePublic, buffer, encoding) {
try {
buffer = _.isString(buffer) ? Buffer.from(buffer, 'base64') : buffer;
var res = this.keyPair.decrypt(buffer, usePublic);
if (res === null) {
throw Error('Key decrypt method returns null.');
}
return this.$getDecryptedData(res, encoding);
} catch (e) {
throw Error('Error during decryption (probably incorrect key). Original error: ' + e);
}
};
/**
* Signing data
*
* @param buffer {string|number|object|array|Buffer} - data for signing. Object and array will convert to JSON string.
* @param encoding {string} - optional. Encoding for output result, may be 'buffer', 'binary', 'hex' or 'base64'. Default 'buffer'.
* @param source_encoding {string} - optional. Encoding for given string. Default utf8.
* @returns {string|Buffer}
*/
NodeRSA.prototype.sign = function (buffer, encoding, source_encoding) {
if (!this.isPrivate()) {
throw Error("This is not private key");
}
var res = this.keyPair.sign(this.$getDataForEncrypt(buffer, source_encoding));
if (encoding && encoding != 'buffer') {
res = res.toString(encoding);
}
return res;
};
/**
* Verifying signed data
*
* @param buffer - signed data
* @param signature
* @param source_encoding {string} - optional. Encoding for given string. Default utf8.
* @param signature_encoding - optional. Encoding of given signature. May be 'buffer', 'binary', 'hex' or 'base64'. Default 'buffer'.
* @returns {*}
*/
NodeRSA.prototype.verify = function (buffer, signature, source_encoding, signature_encoding) {
if (!this.isPublic()) {
throw Error("This is not public key");
}
signature_encoding = (!signature_encoding || signature_encoding == 'buffer' ? null : signature_encoding);
return this.keyPair.verify(this.$getDataForEncrypt(buffer, source_encoding), signature, signature_encoding);
};
/**
* Returns key size in bits
* @returns {int}
*/
NodeRSA.prototype.getKeySize = function () {
return this.keyPair.keySize;
};
/**
* Returns max message length in bytes (for 1 chunk) depending on current encryption scheme
* @returns {int}
*/
NodeRSA.prototype.getMaxMessageSize = function () {
return this.keyPair.maxMessageLength;
};
/**
* Preparing given data for encrypting/signing. Just make new/return Buffer object.
*
* @param buffer {string|number|object|array|Buffer} - data for encrypting. Object and array will convert to JSON string.
* @param encoding {string} - optional. Encoding for given string. Default utf8.
* @returns {Buffer}
*/
NodeRSA.prototype.$getDataForEncrypt = function (buffer, encoding) {
if (_.isString(buffer) || _.isNumber(buffer)) {
return Buffer.from('' + buffer, encoding || 'utf8');
} else if (Buffer.isBuffer(buffer)) {
return buffer;
} else if (_.isObject(buffer)) {
return Buffer.from(JSON.stringify(buffer));
} else {
throw Error("Unexpected data type");
}
};
/**
*
* @param buffer {Buffer} - decrypted data.
* @param encoding - optional. Encoding for result output. May be 'buffer', 'json' or any of Node.js Buffer supported encoding.
* @returns {*}
*/
NodeRSA.prototype.$getDecryptedData = function (buffer, encoding) {
encoding = encoding || 'buffer';
if (encoding == 'buffer') {
return buffer;
} else if (encoding == 'json') {
return JSON.parse(buffer.toString());
} else {
return buffer.toString(encoding);
}
};
return NodeRSA;
})();

View File

@ -0,0 +1,17 @@
var crypt = require('crypto');
module.exports = {
getEngine: function (keyPair, options) {
var engine = require('./js.js');
if (options.environment === 'node') {
if (typeof crypt.publicEncrypt === 'function' && typeof crypt.privateDecrypt === 'function') {
if (typeof crypt.privateEncrypt === 'function' && typeof crypt.publicDecrypt === 'function') {
engine = require('./io.js');
} else {
engine = require('./node12.js');
}
}
}
return engine(keyPair, options);
}
};

72
node_modules/node-rsa/src/encryptEngines/io.js generated vendored Normal file
View File

@ -0,0 +1,72 @@
var crypto = require('crypto');
var constants = require('constants');
var schemes = require('../schemes/schemes.js');
module.exports = function (keyPair, options) {
var pkcs1Scheme = schemes.pkcs1.makeScheme(keyPair, options);
return {
encrypt: function (buffer, usePrivate) {
var padding;
if (usePrivate) {
padding = constants.RSA_PKCS1_PADDING;
if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) {
padding = options.encryptionSchemeOptions.padding;
}
return crypto.privateEncrypt({
key: options.rsaUtils.exportKey('private'),
padding: padding
}, buffer);
} else {
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);
}
},
decrypt: function (buffer, usePublic) {
var padding;
if (usePublic) {
padding = constants.RSA_PKCS1_PADDING;
if (options.encryptionSchemeOptions && options.encryptionSchemeOptions.padding) {
padding = options.encryptionSchemeOptions.padding;
}
return crypto.publicDecrypt({
key: options.rsaUtils.exportKey('public'),
padding: padding
}, buffer);
} else {
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 res = crypto.privateDecrypt({
key: options.rsaUtils.exportKey('private'),
padding: padding
}, buffer);
if (padding === constants.RSA_NO_PADDING) {
return pkcs1Scheme.pkcs0unpad(res);
}
return res;
}
}
};
};

34
node_modules/node-rsa/src/encryptEngines/js.js generated vendored Normal file
View File

@ -0,0 +1,34 @@
var BigInteger = require('../libs/jsbn.js');
var schemes = require('../schemes/schemes.js');
module.exports = function (keyPair, options) {
var pkcs1Scheme = schemes.pkcs1.makeScheme(keyPair, options);
return {
encrypt: function (buffer, usePrivate) {
var m, c;
if (usePrivate) {
/* Type 1: zeros padding for private key encrypt */
m = new BigInteger(pkcs1Scheme.encPad(buffer, {type: 1}));
c = keyPair.$doPrivate(m);
} else {
m = new BigInteger(keyPair.encryptionScheme.encPad(buffer));
c = keyPair.$doPublic(m);
}
return c.toBuffer(keyPair.encryptedDataLength);
},
decrypt: function (buffer, usePublic) {
var m, c = new BigInteger(buffer);
if (usePublic) {
m = keyPair.$doPublic(c);
/* Type 1: zeros padding for private key decrypt */
return pkcs1Scheme.encUnPad(m.toBuffer(keyPair.encryptedDataLength), {type: 1});
} else {
m = keyPair.$doPrivate(c);
return keyPair.encryptionScheme.encUnPad(m.toBuffer(keyPair.encryptedDataLength));
}
}
};
};

56
node_modules/node-rsa/src/encryptEngines/node12.js generated vendored Normal file
View File

@ -0,0 +1,56 @@
var crypto = require('crypto');
var constants = require('constants');
var schemes = require('../schemes/schemes.js');
module.exports = function (keyPair, options) {
var jsEngine = require('./js.js')(keyPair, options);
var pkcs1Scheme = schemes.pkcs1.makeScheme(keyPair, options);
return {
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);
},
decrypt: function (buffer, usePublic) {
if (usePublic) {
return jsEngine.decrypt(buffer, usePublic);
}
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 res = crypto.privateDecrypt({
key: options.rsaUtils.exportKey('private'),
padding: padding
}, buffer);
if (padding === constants.RSA_NO_PADDING) {
return pkcs1Scheme.pkcs0unpad(res);
}
return res;
}
};
};

71
node_modules/node-rsa/src/formats/components.js generated vendored Normal file
View File

@ -0,0 +1,71 @@
var _ = require('../utils')._;
var utils = require('../utils');
module.exports = {
privateExport: function (key, options) {
return {
n: key.n.toBuffer(),
e: key.e,
d: key.d.toBuffer(),
p: key.p.toBuffer(),
q: key.q.toBuffer(),
dmp1: key.dmp1.toBuffer(),
dmq1: key.dmq1.toBuffer(),
coeff: key.coeff.toBuffer()
};
},
privateImport: function (key, data, options) {
if (data.n && data.e && data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff) {
key.setPrivate(
data.n,
data.e,
data.d,
data.p,
data.q,
data.dmp1,
data.dmq1,
data.coeff
);
} else {
throw Error("Invalid key data");
}
},
publicExport: function (key, options) {
return {
n: key.n.toBuffer(),
e: key.e
};
},
publicImport: function (key, data, options) {
if (data.n && data.e) {
key.setPublic(
data.n,
data.e
);
} else {
throw Error("Invalid key data");
}
},
/**
* Trying autodetect and import key
* @param key
* @param data
*/
autoImport: function (key, data) {
if (data.n && data.e) {
if (data.d && data.p && data.q && data.dmp1 && data.dmq1 && data.coeff) {
module.exports.privateImport(key, data);
return true;
} else {
module.exports.publicImport(key, data);
return true;
}
}
return false;
}
};

97
node_modules/node-rsa/src/formats/formats.js generated vendored Normal file
View File

@ -0,0 +1,97 @@
var _ = require('../utils')._;
function formatParse(format) {
format = format.split('-');
var keyType = 'private';
var keyOpt = {type: 'default'};
for (var i = 1; i < format.length; i++) {
if (format[i]) {
switch (format[i]) {
case 'public':
keyType = format[i];
break;
case 'private':
keyType = format[i];
break;
case 'pem':
keyOpt.type = format[i];
break;
case 'der':
keyOpt.type = format[i];
break;
}
}
}
return {scheme: format[0], keyType: keyType, keyOpt: keyOpt};
}
module.exports = {
pkcs1: require('./pkcs1'),
pkcs8: require('./pkcs8'),
components: require('./components'),
openssh: require('./openssh'),
isPrivateExport: function (format) {
return module.exports[format] && typeof module.exports[format].privateExport === 'function';
},
isPrivateImport: function (format) {
return module.exports[format] && typeof module.exports[format].privateImport === 'function';
},
isPublicExport: function (format) {
return module.exports[format] && typeof module.exports[format].publicExport === 'function';
},
isPublicImport: function (format) {
return module.exports[format] && typeof module.exports[format].publicImport === 'function';
},
detectAndImport: function (key, data, format) {
if (format === undefined) {
for (var scheme in module.exports) {
if (typeof module.exports[scheme].autoImport === 'function' && module.exports[scheme].autoImport(key, data)) {
return true;
}
}
} else if (format) {
var fmt = formatParse(format);
if (module.exports[fmt.scheme]) {
if (fmt.keyType === 'private') {
module.exports[fmt.scheme].privateImport(key, data, fmt.keyOpt);
} else {
module.exports[fmt.scheme].publicImport(key, data, fmt.keyOpt);
}
} else {
throw Error('Unsupported key format');
}
}
return false;
},
detectAndExport: function (key, format) {
if (format) {
var fmt = formatParse(format);
if (module.exports[fmt.scheme]) {
if (fmt.keyType === 'private') {
if (!key.isPrivate()) {
throw Error("This is not private key");
}
return module.exports[fmt.scheme].privateExport(key, fmt.keyOpt);
} else {
if (!key.isPublic()) {
throw Error("This is not public key");
}
return module.exports[fmt.scheme].publicExport(key, fmt.keyOpt);
}
} else {
throw Error('Unsupported key format');
}
}
}
};

292
node_modules/node-rsa/src/formats/openssh.js generated vendored Normal file
View File

@ -0,0 +1,292 @@
var _ = require("../utils")._;
var utils = require("../utils");
var BigInteger = require("../libs/jsbn");
const PRIVATE_OPENING_BOUNDARY = "-----BEGIN OPENSSH PRIVATE KEY-----";
const PRIVATE_CLOSING_BOUNDARY = "-----END OPENSSH PRIVATE KEY-----";
module.exports = {
privateExport: function (key, options) {
const nbuf = key.n.toBuffer();
let ebuf = Buffer.alloc(4)
ebuf.writeUInt32BE(key.e, 0);
//Slice leading zeroes
while (ebuf[0] === 0) ebuf = ebuf.slice(1);
const dbuf = key.d.toBuffer();
const coeffbuf = key.coeff.toBuffer();
const pbuf = key.p.toBuffer();
const qbuf = key.q.toBuffer();
let commentbuf;
if (typeof key.sshcomment !== "undefined") {
commentbuf = Buffer.from(key.sshcomment);
} else {
commentbuf = Buffer.from([]);
}
const pubkeyLength =
11 + // 32bit length, 'ssh-rsa'
4 + ebuf.byteLength +
4 + nbuf.byteLength;
const privateKeyLength =
8 + //64bit unused checksum
11 + // 32bit length, 'ssh-rsa'
4 + nbuf.byteLength +
4 + ebuf.byteLength +
4 + dbuf.byteLength +
4 + coeffbuf.byteLength +
4 + pbuf.byteLength +
4 + qbuf.byteLength +
4 + commentbuf.byteLength;
let length =
15 + //openssh-key-v1,0x00,
16 + // 2*(32bit length, 'none')
4 + // 32bit length, empty string
4 + // 32bit number of keys
4 + // 32bit pubkey length
pubkeyLength +
4 + //32bit private+checksum+comment+padding length
privateKeyLength;
const paddingLength = Math.ceil(privateKeyLength / 8) * 8 - privateKeyLength;
length += paddingLength;
const buf = Buffer.alloc(length);
const writer = {buf: buf, off: 0};
buf.write("openssh-key-v1", "utf8");
buf.writeUInt8(0, 14);
writer.off += 15;
writeOpenSSHKeyString(writer, Buffer.from("none"));
writeOpenSSHKeyString(writer, Buffer.from("none"));
writeOpenSSHKeyString(writer, Buffer.from(""));
writer.off = writer.buf.writeUInt32BE(1, writer.off);
writer.off = writer.buf.writeUInt32BE(pubkeyLength, writer.off);
writeOpenSSHKeyString(writer, Buffer.from("ssh-rsa"));
writeOpenSSHKeyString(writer, ebuf);
writeOpenSSHKeyString(writer, nbuf);
writer.off = writer.buf.writeUInt32BE(
length - 47 - pubkeyLength,
writer.off
);
writer.off += 8;
writeOpenSSHKeyString(writer, Buffer.from("ssh-rsa"));
writeOpenSSHKeyString(writer, nbuf);
writeOpenSSHKeyString(writer, ebuf);
writeOpenSSHKeyString(writer, dbuf);
writeOpenSSHKeyString(writer, coeffbuf);
writeOpenSSHKeyString(writer, pbuf);
writeOpenSSHKeyString(writer, qbuf);
writeOpenSSHKeyString(writer, commentbuf);
let pad = 0x01;
while (writer.off < length) {
writer.off = writer.buf.writeUInt8(pad++, writer.off);
}
if (options.type === "der") {
return writer.buf
} else {
return PRIVATE_OPENING_BOUNDARY + "\n" + utils.linebrk(buf.toString("base64"), 70) + "\n" + PRIVATE_CLOSING_BOUNDARY + "\n";
}
},
privateImport: function (key, data, options) {
options = options || {};
var buffer;
if (options.type !== "der") {
if (Buffer.isBuffer(data)) {
data = data.toString("utf8");
}
if (_.isString(data)) {
var pem = utils.trimSurroundingText(data, PRIVATE_OPENING_BOUNDARY, PRIVATE_CLOSING_BOUNDARY)
.replace(/\s+|\n\r|\n|\r$/gm, "");
buffer = Buffer.from(pem, "base64");
} else {
throw Error("Unsupported key format");
}
} else if (Buffer.isBuffer(data)) {
buffer = data;
} else {
throw Error("Unsupported key format");
}
const reader = {buf: buffer, off: 0};
if (buffer.slice(0, 14).toString("ascii") !== "openssh-key-v1")
throw "Invalid file format.";
reader.off += 15;
//ciphername
if (readOpenSSHKeyString(reader).toString("ascii") !== "none")
throw Error("Unsupported key type");
//kdfname
if (readOpenSSHKeyString(reader).toString("ascii") !== "none")
throw Error("Unsupported key type");
//kdf
if (readOpenSSHKeyString(reader).toString("ascii") !== "")
throw Error("Unsupported key type");
//keynum
reader.off += 4;
//sshpublength
reader.off += 4;
//keytype
if (readOpenSSHKeyString(reader).toString("ascii") !== "ssh-rsa")
throw Error("Unsupported key type");
readOpenSSHKeyString(reader);
readOpenSSHKeyString(reader);
reader.off += 12;
if (readOpenSSHKeyString(reader).toString("ascii") !== "ssh-rsa")
throw Error("Unsupported key type");
const n = readOpenSSHKeyString(reader);
const e = readOpenSSHKeyString(reader);
const d = readOpenSSHKeyString(reader);
const coeff = readOpenSSHKeyString(reader);
const p = readOpenSSHKeyString(reader);
const q = readOpenSSHKeyString(reader);
//Calculate missing values
const dint = new BigInteger(d);
const qint = new BigInteger(q);
const pint = new BigInteger(p);
const dp = dint.mod(pint.subtract(BigInteger.ONE));
const dq = dint.mod(qint.subtract(BigInteger.ONE));
key.setPrivate(
n, // modulus
e, // publicExponent
d, // privateExponent
p, // prime1
q, // prime2
dp.toBuffer(), // exponent1 -- d mod (p1)
dq.toBuffer(), // exponent2 -- d mod (q-1)
coeff // coefficient -- (inverse of q) mod p
);
key.sshcomment = readOpenSSHKeyString(reader).toString("ascii");
},
publicExport: function (key, options) {
let ebuf = Buffer.alloc(4)
ebuf.writeUInt32BE(key.e, 0);
//Slice leading zeroes
while (ebuf[0] === 0) ebuf = ebuf.slice(1);
const nbuf = key.n.toBuffer();
const buf = Buffer.alloc(
ebuf.byteLength + 4 +
nbuf.byteLength + 4 +
"ssh-rsa".length + 4
);
const writer = {buf: buf, off: 0};
writeOpenSSHKeyString(writer, Buffer.from("ssh-rsa"));
writeOpenSSHKeyString(writer, ebuf);
writeOpenSSHKeyString(writer, nbuf);
let comment = key.sshcomment || "";
if (options.type === "der") {
return writer.buf
} else {
return "ssh-rsa " + buf.toString("base64") + " " + comment + "\n";
}
},
publicImport: function (key, data, options) {
options = options || {};
var buffer;
if (options.type !== "der") {
if (Buffer.isBuffer(data)) {
data = data.toString("utf8");
}
if (_.isString(data)) {
if (data.substring(0, 8) !== "ssh-rsa ")
throw Error("Unsupported key format");
let pemEnd = data.indexOf(" ", 8);
//Handle keys with no comment
if (pemEnd === -1) {
pemEnd = data.length;
} else {
key.sshcomment = data.substring(pemEnd + 1)
.replace(/\s+|\n\r|\n|\r$/gm, "");
}
const pem = data.substring(8, pemEnd)
.replace(/\s+|\n\r|\n|\r$/gm, "");
buffer = Buffer.from(pem, "base64");
} else {
throw Error("Unsupported key format");
}
} else if (Buffer.isBuffer(data)) {
buffer = data;
} else {
throw Error("Unsupported key format");
}
const reader = {buf: buffer, off: 0};
const type = readOpenSSHKeyString(reader).toString("ascii");
if (type !== "ssh-rsa")
throw Error("Invalid key type: " + type);
const e = readOpenSSHKeyString(reader);
const n = readOpenSSHKeyString(reader);
key.setPublic(
n,
e
);
},
/**
* Trying autodetect and import key
* @param key
* @param data
*/
autoImport: function (key, data) {
// [\S\s]* matches zero or more of any character
if (/^[\S\s]*-----BEGIN OPENSSH PRIVATE KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END OPENSSH PRIVATE KEY-----[\S\s]*$/g.test(data)) {
module.exports.privateImport(key, data);
return true;
}
if (/^[\S\s]*ssh-rsa \s*(?=(([A-Za-z0-9+/=]+\s*)+))\1[\S\s]*$/g.test(data)) {
module.exports.publicImport(key, data);
return true;
}
return false;
}
};
function readOpenSSHKeyString(reader) {
const len = reader.buf.readInt32BE(reader.off);
reader.off += 4;
const res = reader.buf.slice(reader.off, reader.off + len);
reader.off += len;
return res;
}
function writeOpenSSHKeyString(writer, data) {
writer.buf.writeInt32BE(data.byteLength, writer.off);
writer.off += 4;
writer.off += data.copy(writer.buf, writer.off);
}

148
node_modules/node-rsa/src/formats/pkcs1.js generated vendored Normal file
View File

@ -0,0 +1,148 @@
var ber = require('asn1').Ber;
var _ = require('../utils')._;
var utils = require('../utils');
const PRIVATE_OPENING_BOUNDARY = '-----BEGIN RSA PRIVATE KEY-----';
const PRIVATE_CLOSING_BOUNDARY = '-----END RSA PRIVATE KEY-----';
const PUBLIC_OPENING_BOUNDARY = '-----BEGIN RSA PUBLIC KEY-----';
const PUBLIC_CLOSING_BOUNDARY = '-----END RSA PUBLIC KEY-----';
module.exports = {
privateExport: function (key, options) {
options = options || {};
var n = key.n.toBuffer();
var d = key.d.toBuffer();
var p = key.p.toBuffer();
var q = key.q.toBuffer();
var dmp1 = key.dmp1.toBuffer();
var dmq1 = key.dmq1.toBuffer();
var coeff = key.coeff.toBuffer();
var length = n.length + d.length + p.length + q.length + dmp1.length + dmq1.length + coeff.length + 512; // magic
var writer = new ber.Writer({size: length});
writer.startSequence();
writer.writeInt(0);
writer.writeBuffer(n, 2);
writer.writeInt(key.e);
writer.writeBuffer(d, 2);
writer.writeBuffer(p, 2);
writer.writeBuffer(q, 2);
writer.writeBuffer(dmp1, 2);
writer.writeBuffer(dmq1, 2);
writer.writeBuffer(coeff, 2);
writer.endSequence();
if (options.type === 'der') {
return writer.buffer;
} else {
return PRIVATE_OPENING_BOUNDARY + '\n' + utils.linebrk(writer.buffer.toString('base64'), 64) + '\n' + PRIVATE_CLOSING_BOUNDARY;
}
},
privateImport: function (key, data, options) {
options = options || {};
var buffer;
if (options.type !== 'der') {
if (Buffer.isBuffer(data)) {
data = data.toString('utf8');
}
if (_.isString(data)) {
var pem = utils.trimSurroundingText(data, PRIVATE_OPENING_BOUNDARY, PRIVATE_CLOSING_BOUNDARY)
.replace(/\s+|\n\r|\n|\r$/gm, '');
buffer = Buffer.from(pem, 'base64');
} else {
throw Error('Unsupported key format');
}
} else if (Buffer.isBuffer(data)) {
buffer = data;
} else {
throw Error('Unsupported key format');
}
var reader = new ber.Reader(buffer);
reader.readSequence();
reader.readString(2, true); // just zero
key.setPrivate(
reader.readString(2, true), // modulus
reader.readString(2, true), // publicExponent
reader.readString(2, true), // privateExponent
reader.readString(2, true), // prime1
reader.readString(2, true), // prime2
reader.readString(2, true), // exponent1 -- d mod (p1)
reader.readString(2, true), // exponent2 -- d mod (q-1)
reader.readString(2, true) // coefficient -- (inverse of q) mod p
);
},
publicExport: function (key, options) {
options = options || {};
var n = key.n.toBuffer();
var length = n.length + 512; // magic
var bodyWriter = new ber.Writer({size: length});
bodyWriter.startSequence();
bodyWriter.writeBuffer(n, 2);
bodyWriter.writeInt(key.e);
bodyWriter.endSequence();
if (options.type === 'der') {
return bodyWriter.buffer;
} else {
return PUBLIC_OPENING_BOUNDARY + '\n' + utils.linebrk(bodyWriter.buffer.toString('base64'), 64) + '\n' + PUBLIC_CLOSING_BOUNDARY;
}
},
publicImport: function (key, data, options) {
options = options || {};
var buffer;
if (options.type !== 'der') {
if (Buffer.isBuffer(data)) {
data = data.toString('utf8');
}
if (_.isString(data)) {
var pem = utils.trimSurroundingText(data, PUBLIC_OPENING_BOUNDARY, PUBLIC_CLOSING_BOUNDARY)
.replace(/\s+|\n\r|\n|\r$/gm, '');
buffer = Buffer.from(pem, 'base64');
}
} else if (Buffer.isBuffer(data)) {
buffer = data;
} else {
throw Error('Unsupported key format');
}
var body = new ber.Reader(buffer);
body.readSequence();
key.setPublic(
body.readString(0x02, true), // modulus
body.readString(0x02, true) // publicExponent
);
},
/**
* Trying autodetect and import key
* @param key
* @param data
*/
autoImport: function (key, data) {
// [\S\s]* matches zero or more of any character
if (/^[\S\s]*-----BEGIN RSA PRIVATE KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END RSA PRIVATE KEY-----[\S\s]*$/g.test(data)) {
module.exports.privateImport(key, data);
return true;
}
if (/^[\S\s]*-----BEGIN RSA PUBLIC KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END RSA PUBLIC KEY-----[\S\s]*$/g.test(data)) {
module.exports.publicImport(key, data);
return true;
}
return false;
}
};

187
node_modules/node-rsa/src/formats/pkcs8.js generated vendored Normal file
View File

@ -0,0 +1,187 @@
var ber = require('asn1').Ber;
var _ = require('../utils')._;
var PUBLIC_RSA_OID = '1.2.840.113549.1.1.1';
var utils = require('../utils');
const PRIVATE_OPENING_BOUNDARY = '-----BEGIN PRIVATE KEY-----';
const PRIVATE_CLOSING_BOUNDARY = '-----END PRIVATE KEY-----';
const PUBLIC_OPENING_BOUNDARY = '-----BEGIN PUBLIC KEY-----';
const PUBLIC_CLOSING_BOUNDARY = '-----END PUBLIC KEY-----';
module.exports = {
privateExport: function (key, options) {
options = options || {};
var n = key.n.toBuffer();
var d = key.d.toBuffer();
var p = key.p.toBuffer();
var q = key.q.toBuffer();
var dmp1 = key.dmp1.toBuffer();
var dmq1 = key.dmq1.toBuffer();
var coeff = key.coeff.toBuffer();
var length = n.length + d.length + p.length + q.length + dmp1.length + dmq1.length + coeff.length + 512; // magic
var bodyWriter = new ber.Writer({size: length});
bodyWriter.startSequence();
bodyWriter.writeInt(0);
bodyWriter.writeBuffer(n, 2);
bodyWriter.writeInt(key.e);
bodyWriter.writeBuffer(d, 2);
bodyWriter.writeBuffer(p, 2);
bodyWriter.writeBuffer(q, 2);
bodyWriter.writeBuffer(dmp1, 2);
bodyWriter.writeBuffer(dmq1, 2);
bodyWriter.writeBuffer(coeff, 2);
bodyWriter.endSequence();
var writer = new ber.Writer({size: length});
writer.startSequence();
writer.writeInt(0);
writer.startSequence();
writer.writeOID(PUBLIC_RSA_OID);
writer.writeNull();
writer.endSequence();
writer.writeBuffer(bodyWriter.buffer, 4);
writer.endSequence();
if (options.type === 'der') {
return writer.buffer;
} else {
return PRIVATE_OPENING_BOUNDARY + '\n' + utils.linebrk(writer.buffer.toString('base64'), 64) + '\n' + PRIVATE_CLOSING_BOUNDARY;
}
},
privateImport: function (key, data, options) {
options = options || {};
var buffer;
if (options.type !== 'der') {
if (Buffer.isBuffer(data)) {
data = data.toString('utf8');
}
if (_.isString(data)) {
var pem = utils.trimSurroundingText(data, PRIVATE_OPENING_BOUNDARY, PRIVATE_CLOSING_BOUNDARY)
.replace('-----END PRIVATE KEY-----', '')
.replace(/\s+|\n\r|\n|\r$/gm, '');
buffer = Buffer.from(pem, 'base64');
} else {
throw Error('Unsupported key format');
}
} else if (Buffer.isBuffer(data)) {
buffer = data;
} else {
throw Error('Unsupported key format');
}
var reader = new ber.Reader(buffer);
reader.readSequence();
reader.readInt(0);
var header = new ber.Reader(reader.readString(0x30, true));
if (header.readOID(0x06, true) !== PUBLIC_RSA_OID) {
throw Error('Invalid Public key format');
}
var body = new ber.Reader(reader.readString(0x04, true));
body.readSequence();
body.readString(2, true); // just zero
key.setPrivate(
body.readString(2, true), // modulus
body.readString(2, true), // publicExponent
body.readString(2, true), // privateExponent
body.readString(2, true), // prime1
body.readString(2, true), // prime2
body.readString(2, true), // exponent1 -- d mod (p1)
body.readString(2, true), // exponent2 -- d mod (q-1)
body.readString(2, true) // coefficient -- (inverse of q) mod p
);
},
publicExport: function (key, options) {
options = options || {};
var n = key.n.toBuffer();
var length = n.length + 512; // magic
var bodyWriter = new ber.Writer({size: length});
bodyWriter.writeByte(0);
bodyWriter.startSequence();
bodyWriter.writeBuffer(n, 2);
bodyWriter.writeInt(key.e);
bodyWriter.endSequence();
var writer = new ber.Writer({size: length});
writer.startSequence();
writer.startSequence();
writer.writeOID(PUBLIC_RSA_OID);
writer.writeNull();
writer.endSequence();
writer.writeBuffer(bodyWriter.buffer, 3);
writer.endSequence();
if (options.type === 'der') {
return writer.buffer;
} else {
return PUBLIC_OPENING_BOUNDARY + '\n' + utils.linebrk(writer.buffer.toString('base64'), 64) + '\n' + PUBLIC_CLOSING_BOUNDARY;
}
},
publicImport: function (key, data, options) {
options = options || {};
var buffer;
if (options.type !== 'der') {
if (Buffer.isBuffer(data)) {
data = data.toString('utf8');
}
if (_.isString(data)) {
var pem = utils.trimSurroundingText(data, PUBLIC_OPENING_BOUNDARY, PUBLIC_CLOSING_BOUNDARY)
.replace(/\s+|\n\r|\n|\r$/gm, '');
buffer = Buffer.from(pem, 'base64');
}
} else if (Buffer.isBuffer(data)) {
buffer = data;
} else {
throw Error('Unsupported key format');
}
var reader = new ber.Reader(buffer);
reader.readSequence();
var header = new ber.Reader(reader.readString(0x30, true));
if (header.readOID(0x06, true) !== PUBLIC_RSA_OID) {
throw Error('Invalid Public key format');
}
var body = new ber.Reader(reader.readString(0x03, true));
body.readByte();
body.readSequence();
key.setPublic(
body.readString(0x02, true), // modulus
body.readString(0x02, true) // publicExponent
);
},
/**
* Trying autodetect and import key
* @param key
* @param data
*/
autoImport: function (key, data) {
if (/^[\S\s]*-----BEGIN PRIVATE KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END PRIVATE KEY-----[\S\s]*$/g.test(data)) {
module.exports.privateImport(key, data);
return true;
}
if (/^[\S\s]*-----BEGIN PUBLIC KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END PUBLIC KEY-----[\S\s]*$/g.test(data)) {
module.exports.publicImport(key, data);
return true;
}
return false;
}
};

1540
node_modules/node-rsa/src/libs/jsbn.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

316
node_modules/node-rsa/src/libs/rsa.js generated vendored Normal file
View File

@ -0,0 +1,316 @@
/*
* RSA Encryption / Decryption with PKCS1 v2 Padding.
*
* Copyright (c) 2003-2005 Tom Wu
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
* THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* In addition, the following condition applies:
*
* All redistributions must retain an intact copy of this copyright notice
* and disclaimer.
*/
/*
* Node.js adaptation
* long message support implementation
* signing/verifying
*
* 2014 rzcoder
*/
var _ = require('../utils')._;
var crypt = require('crypto');
var BigInteger = require('./jsbn.js');
var utils = require('../utils.js');
var schemes = require('../schemes/schemes.js');
var encryptEngines = require('../encryptEngines/encryptEngines.js');
exports.BigInteger = BigInteger;
module.exports.Key = (function () {
/**
* RSA key constructor
*
* n - modulus
* e - publicExponent
* d - privateExponent
* p - prime1
* q - prime2
* dmp1 - exponent1 -- d mod (p1)
* dmq1 - exponent2 -- d mod (q-1)
* coeff - coefficient -- (inverse of q) mod p
*/
function RSAKey() {
this.n = null;
this.e = 0;
this.d = null;
this.p = null;
this.q = null;
this.dmp1 = null;
this.dmq1 = null;
this.coeff = null;
}
RSAKey.prototype.setOptions = function (options) {
var signingSchemeProvider = schemes[options.signingScheme];
var encryptionSchemeProvider = schemes[options.encryptionScheme];
if (signingSchemeProvider === encryptionSchemeProvider) {
this.signingScheme = this.encryptionScheme = encryptionSchemeProvider.makeScheme(this, options);
} else {
this.encryptionScheme = encryptionSchemeProvider.makeScheme(this, options);
this.signingScheme = signingSchemeProvider.makeScheme(this, options);
}
this.encryptEngine = encryptEngines.getEngine(this, options);
};
/**
* Generate a new random private key B bits long, using public expt E
* @param B
* @param E
*/
RSAKey.prototype.generate = function (B, E) {
var qs = B >> 1;
this.e = parseInt(E, 16);
var ee = new BigInteger(E, 16);
while (true) {
while (true) {
this.p = new BigInteger(B - qs, 1);
if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) === 0 && this.p.isProbablePrime(10))
break;
}
while (true) {
this.q = new BigInteger(qs, 1);
if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) === 0 && this.q.isProbablePrime(10))
break;
}
if (this.p.compareTo(this.q) <= 0) {
var t = this.p;
this.p = this.q;
this.q = t;
}
var p1 = this.p.subtract(BigInteger.ONE);
var q1 = this.q.subtract(BigInteger.ONE);
var phi = p1.multiply(q1);
if (phi.gcd(ee).compareTo(BigInteger.ONE) === 0) {
this.n = this.p.multiply(this.q);
if (this.n.bitLength() < B) {
continue;
}
this.d = ee.modInverse(phi);
this.dmp1 = this.d.mod(p1);
this.dmq1 = this.d.mod(q1);
this.coeff = this.q.modInverse(this.p);
break;
}
}
this.$$recalculateCache();
};
/**
* Set the private key fields N, e, d and CRT params from buffers
*
* @param N
* @param E
* @param D
* @param P
* @param Q
* @param DP
* @param DQ
* @param C
*/
RSAKey.prototype.setPrivate = function (N, E, D, P, Q, DP, DQ, C) {
if (N && E && D && N.length > 0 && (_.isNumber(E) || E.length > 0) && D.length > 0) {
this.n = new BigInteger(N);
this.e = _.isNumber(E) ? E : utils.get32IntFromBuffer(E, 0);
this.d = new BigInteger(D);
if (P && Q && DP && DQ && C) {
this.p = new BigInteger(P);
this.q = new BigInteger(Q);
this.dmp1 = new BigInteger(DP);
this.dmq1 = new BigInteger(DQ);
this.coeff = new BigInteger(C);
} else {
// TODO: re-calculate any missing CRT params
}
this.$$recalculateCache();
} else {
throw Error("Invalid RSA private key");
}
};
/**
* Set the public key fields N and e from hex strings
* @param N
* @param E
*/
RSAKey.prototype.setPublic = function (N, E) {
if (N && E && N.length > 0 && (_.isNumber(E) || E.length > 0)) {
this.n = new BigInteger(N);
this.e = _.isNumber(E) ? E : utils.get32IntFromBuffer(E, 0);
this.$$recalculateCache();
} else {
throw Error("Invalid RSA public key");
}
};
/**
* private
* Perform raw private operation on "x": return x^d (mod n)
*
* @param x
* @returns {*}
*/
RSAKey.prototype.$doPrivate = function (x) {
if (this.p || this.q) {
return x.modPow(this.d, this.n);
}
// TODO: re-calculate any missing CRT params
var xp = x.mod(this.p).modPow(this.dmp1, this.p);
var xq = x.mod(this.q).modPow(this.dmq1, this.q);
while (xp.compareTo(xq) < 0) {
xp = xp.add(this.p);
}
return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
};
/**
* private
* Perform raw public operation on "x": return x^e (mod n)
*
* @param x
* @returns {*}
*/
RSAKey.prototype.$doPublic = function (x) {
return x.modPowInt(this.e, this.n);
};
/**
* Return the PKCS#1 RSA encryption of buffer
* @param buffer {Buffer}
* @returns {Buffer}
*/
RSAKey.prototype.encrypt = function (buffer, usePrivate) {
var buffers = [];
var results = [];
var bufferSize = buffer.length;
var buffersCount = Math.ceil(bufferSize / this.maxMessageLength) || 1; // total buffers count for encrypt
var dividedSize = Math.ceil(bufferSize / buffersCount || 1); // each buffer size
if (buffersCount == 1) {
buffers.push(buffer);
} else {
for (var bufNum = 0; bufNum < buffersCount; bufNum++) {
buffers.push(buffer.slice(bufNum * dividedSize, (bufNum + 1) * dividedSize));
}
}
for (var i = 0; i < buffers.length; i++) {
results.push(this.encryptEngine.encrypt(buffers[i], usePrivate));
}
return Buffer.concat(results);
};
/**
* Return the PKCS#1 RSA decryption of buffer
* @param buffer {Buffer}
* @returns {Buffer}
*/
RSAKey.prototype.decrypt = function (buffer, usePublic) {
if (buffer.length % this.encryptedDataLength > 0) {
throw Error('Incorrect data or key');
}
var result = [];
var offset = 0;
var length = 0;
var buffersCount = buffer.length / this.encryptedDataLength;
for (var i = 0; i < buffersCount; i++) {
offset = i * this.encryptedDataLength;
length = offset + this.encryptedDataLength;
result.push(this.encryptEngine.decrypt(buffer.slice(offset, Math.min(length, buffer.length)), usePublic));
}
return Buffer.concat(result);
};
RSAKey.prototype.sign = function (buffer) {
return this.signingScheme.sign.apply(this.signingScheme, arguments);
};
RSAKey.prototype.verify = function (buffer, signature, signature_encoding) {
return this.signingScheme.verify.apply(this.signingScheme, arguments);
};
/**
* Check if key pair contains private key
*/
RSAKey.prototype.isPrivate = function () {
return this.n && this.e && this.d && true || false;
};
/**
* Check if key pair contains public key
* @param strict {boolean} - public key only, return false if have private exponent
*/
RSAKey.prototype.isPublic = function (strict) {
return this.n && this.e && !(strict && this.d) || false;
};
Object.defineProperty(RSAKey.prototype, 'keySize', {
get: function () {
return this.cache.keyBitLength;
}
});
Object.defineProperty(RSAKey.prototype, 'encryptedDataLength', {
get: function () {
return this.cache.keyByteLength;
}
});
Object.defineProperty(RSAKey.prototype, 'maxMessageLength', {
get: function () {
return this.encryptionScheme.maxMessageLength();
}
});
/**
* Caching key data
*/
RSAKey.prototype.$$recalculateCache = function () {
this.cache = this.cache || {};
// Bit & byte length
this.cache.keyBitLength = this.n.bitLength();
this.cache.keyByteLength = (this.cache.keyBitLength + 6) >> 3;
};
return RSAKey;
})();

179
node_modules/node-rsa/src/schemes/oaep.js generated vendored Normal file
View File

@ -0,0 +1,179 @@
/**
* PKCS_OAEP signature scheme
*/
var BigInteger = require('../libs/jsbn');
var crypt = require('crypto');
module.exports = {
isEncryption: true,
isSignature: false
};
module.exports.digestLength = {
md4: 16,
md5: 16,
ripemd160: 20,
rmd160: 20,
sha1: 20,
sha224: 28,
sha256: 32,
sha384: 48,
sha512: 64
};
var DEFAULT_HASH_FUNCTION = 'sha1';
/*
* OAEP Mask Generation Function 1
* Generates a buffer full of pseudorandom bytes given seed and maskLength.
* Giving the same seed, maskLength, and hashFunction will result in the same exact byte values in the buffer.
*
* https://tools.ietf.org/html/rfc3447#appendix-B.2.1
*
* Parameters:
* seed [Buffer] The pseudo random seed for this function
* maskLength [int] The length of the output
* hashFunction [String] The hashing function to use. Will accept any valid crypto hash. Default "sha1"
* Supports "sha1" and "sha256".
* To add another algorythm the algorythem must be accepted by crypto.createHash, and then the length of the output of the hash function (the digest) must be added to the digestLength object below.
* Most RSA implementations will be expecting sha1
*/
module.exports.eme_oaep_mgf1 = function (seed, maskLength, hashFunction) {
hashFunction = hashFunction || DEFAULT_HASH_FUNCTION;
var hLen = module.exports.digestLength[hashFunction];
var count = Math.ceil(maskLength / hLen);
var T = Buffer.alloc(hLen * count);
var c = Buffer.alloc(4);
for (var i = 0; i < count; ++i) {
var hash = crypt.createHash(hashFunction);
hash.update(seed);
c.writeUInt32BE(i, 0);
hash.update(c);
hash.digest().copy(T, i * hLen);
}
return T.slice(0, maskLength);
};
module.exports.makeScheme = function (key, options) {
function Scheme(key, options) {
this.key = key;
this.options = options;
}
Scheme.prototype.maxMessageLength = function () {
return this.key.encryptedDataLength - 2 * module.exports.digestLength[this.options.encryptionSchemeOptions.hash || DEFAULT_HASH_FUNCTION] - 2;
};
/**
* Pad input
* alg: PKCS1_OAEP
*
* https://tools.ietf.org/html/rfc3447#section-7.1.1
*/
Scheme.prototype.encPad = function (buffer) {
var hash = this.options.encryptionSchemeOptions.hash || DEFAULT_HASH_FUNCTION;
var mgf = this.options.encryptionSchemeOptions.mgf || module.exports.eme_oaep_mgf1;
var label = this.options.encryptionSchemeOptions.label || Buffer.alloc(0);
var emLen = this.key.encryptedDataLength;
var hLen = module.exports.digestLength[hash];
// Make sure we can put message into an encoded message of emLen bytes
if (buffer.length > emLen - 2 * hLen - 2) {
throw new Error("Message is too long to encode into an encoded message with a length of " + emLen + " bytes, increase" +
"emLen to fix this error (minimum value for given parameters and options: " + (emLen - 2 * hLen - 2) + ")");
}
var lHash = crypt.createHash(hash);
lHash.update(label);
lHash = lHash.digest();
var PS = Buffer.alloc(emLen - buffer.length - 2 * hLen - 1); // Padding "String"
PS.fill(0); // Fill the buffer with octets of 0
PS[PS.length - 1] = 1;
var DB = Buffer.concat([lHash, PS, buffer]);
var seed = crypt.randomBytes(hLen);
// mask = dbMask
var mask = mgf(seed, DB.length, hash);
// XOR DB and dbMask together.
for (var i = 0; i < DB.length; i++) {
DB[i] ^= mask[i];
}
// DB = maskedDB
// mask = seedMask
mask = mgf(DB, hLen, hash);
// XOR seed and seedMask together.
for (i = 0; i < seed.length; i++) {
seed[i] ^= mask[i];
}
// seed = maskedSeed
var em = Buffer.alloc(1 + seed.length + DB.length);
em[0] = 0;
seed.copy(em, 1);
DB.copy(em, 1 + seed.length);
return em;
};
/**
* Unpad input
* alg: PKCS1_OAEP
*
* Note: This method works within the buffer given and modifies the values. It also returns a slice of the EM as the return Message.
* If the implementation requires that the EM parameter be unmodified then the implementation should pass in a clone of the EM buffer.
*
* https://tools.ietf.org/html/rfc3447#section-7.1.2
*/
Scheme.prototype.encUnPad = function (buffer) {
var hash = this.options.encryptionSchemeOptions.hash || DEFAULT_HASH_FUNCTION;
var mgf = this.options.encryptionSchemeOptions.mgf || module.exports.eme_oaep_mgf1;
var label = this.options.encryptionSchemeOptions.label || Buffer.alloc(0);
var hLen = module.exports.digestLength[hash];
// Check to see if buffer is a properly encoded OAEP message
if (buffer.length < 2 * hLen + 2) {
throw new Error("Error decoding message, the supplied message is not long enough to be a valid OAEP encoded message");
}
var seed = buffer.slice(1, hLen + 1); // seed = maskedSeed
var DB = buffer.slice(1 + hLen); // DB = maskedDB
var mask = mgf(DB, hLen, hash); // seedMask
// XOR maskedSeed and seedMask together to get the original seed.
for (var i = 0; i < seed.length; i++) {
seed[i] ^= mask[i];
}
mask = mgf(seed, DB.length, hash); // dbMask
// XOR DB and dbMask together to get the original data block.
for (i = 0; i < DB.length; i++) {
DB[i] ^= mask[i];
}
var lHash = crypt.createHash(hash);
lHash.update(label);
lHash = lHash.digest();
var lHashEM = DB.slice(0, hLen);
if (lHashEM.toString("hex") != lHash.toString("hex")) {
throw new Error("Error decoding message, the lHash calculated from the label provided and the lHash in the encrypted data do not match.");
}
// Filter out padding
i = hLen;
while (DB[i++] === 0 && i < DB.length);
if (DB[i - 1] != 1) {
throw new Error("Error decoding message, there is no padding message separator byte");
}
return DB.slice(i); // Message
};
return new Scheme(key, options);
};

238
node_modules/node-rsa/src/schemes/pkcs1.js generated vendored Normal file
View File

@ -0,0 +1,238 @@
/**
* PKCS1 padding and signature scheme
*/
var BigInteger = require('../libs/jsbn');
var crypt = require('crypto');
var constants = require('constants');
var SIGN_INFO_HEAD = {
md2: Buffer.from('3020300c06082a864886f70d020205000410', 'hex'),
md5: Buffer.from('3020300c06082a864886f70d020505000410', 'hex'),
sha1: Buffer.from('3021300906052b0e03021a05000414', 'hex'),
sha224: Buffer.from('302d300d06096086480165030402040500041c', 'hex'),
sha256: Buffer.from('3031300d060960864801650304020105000420', 'hex'),
sha384: Buffer.from('3041300d060960864801650304020205000430', 'hex'),
sha512: Buffer.from('3051300d060960864801650304020305000440', 'hex'),
ripemd160: Buffer.from('3021300906052b2403020105000414', 'hex'),
rmd160: Buffer.from('3021300906052b2403020105000414', 'hex')
};
var SIGN_ALG_TO_HASH_ALIASES = {
'ripemd160': 'rmd160'
};
var DEFAULT_HASH_FUNCTION = 'sha256';
module.exports = {
isEncryption: true,
isSignature: true
};
module.exports.makeScheme = function (key, options) {
function Scheme(key, options) {
this.key = key;
this.options = options;
}
Scheme.prototype.maxMessageLength = function () {
if (this.options.encryptionSchemeOptions && this.options.encryptionSchemeOptions.padding == constants.RSA_NO_PADDING) {
return this.key.encryptedDataLength;
}
return this.key.encryptedDataLength - 11;
};
/**
* Pad input Buffer to encryptedDataLength bytes, and return Buffer.from
* alg: PKCS#1
* @param buffer
* @returns {Buffer}
*/
Scheme.prototype.encPad = function (buffer, options) {
options = options || {};
var filled;
if (buffer.length > this.key.maxMessageLength) {
throw new Error("Message too long for RSA (n=" + this.key.encryptedDataLength + ", l=" + buffer.length + ")");
}
if (this.options.encryptionSchemeOptions && this.options.encryptionSchemeOptions.padding == constants.RSA_NO_PADDING) {
//RSA_NO_PADDING treated like JAVA left pad with zero character
filled = Buffer.alloc(this.key.maxMessageLength - buffer.length);
filled.fill(0);
return Buffer.concat([filled, buffer]);
}
/* Type 1: zeros padding for private key encrypt */
if (options.type === 1) {
filled = Buffer.alloc(this.key.encryptedDataLength - buffer.length - 1);
filled.fill(0xff, 0, filled.length - 1);
filled[0] = 1;
filled[filled.length - 1] = 0;
return Buffer.concat([filled, buffer]);
} else {
/* random padding for public key encrypt */
filled = Buffer.alloc(this.key.encryptedDataLength - buffer.length);
filled[0] = 0;
filled[1] = 2;
var rand = crypt.randomBytes(filled.length - 3);
for (var i = 0; i < rand.length; i++) {
var r = rand[i];
while (r === 0) { // non-zero only
r = crypt.randomBytes(1)[0];
}
filled[i + 2] = r;
}
filled[filled.length - 1] = 0;
return Buffer.concat([filled, buffer]);
}
};
/**
* Unpad input Buffer and, if valid, return the Buffer object
* alg: PKCS#1 (type 2, random)
* @param buffer
* @returns {Buffer}
*/
Scheme.prototype.encUnPad = function (buffer, options) {
options = options || {};
var i = 0;
if (this.options.encryptionSchemeOptions && this.options.encryptionSchemeOptions.padding == constants.RSA_NO_PADDING) {
//RSA_NO_PADDING treated like JAVA left pad with zero character
var unPad;
if (typeof buffer.lastIndexOf == "function") { //patch for old node version
unPad = buffer.slice(buffer.lastIndexOf('\0') + 1, buffer.length);
} else {
unPad = buffer.slice(String.prototype.lastIndexOf.call(buffer, '\0') + 1, buffer.length);
}
return unPad;
}
if (buffer.length < 4) {
return null;
}
/* Type 1: zeros padding for private key decrypt */
if (options.type === 1) {
if (buffer[0] !== 0 || buffer[1] !== 1) {
return null;
}
i = 3;
while (buffer[i] !== 0) {
if (buffer[i] != 0xFF || ++i >= buffer.length) {
return null;
}
}
} else {
/* random padding for public key decrypt */
if (buffer[0] !== 0 || buffer[1] !== 2) {
return null;
}
i = 3;
while (buffer[i] !== 0) {
if (++i >= buffer.length) {
return null;
}
}
}
return buffer.slice(i + 1, buffer.length);
};
Scheme.prototype.sign = function (buffer) {
var hashAlgorithm = this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION;
if (this.options.environment === 'browser') {
hashAlgorithm = SIGN_ALG_TO_HASH_ALIASES[hashAlgorithm] || hashAlgorithm;
var hasher = crypt.createHash(hashAlgorithm);
hasher.update(buffer);
var hash = this.pkcs1pad(hasher.digest(), hashAlgorithm);
var res = this.key.$doPrivate(new BigInteger(hash)).toBuffer(this.key.encryptedDataLength);
return res;
} else {
var signer = crypt.createSign('RSA-' + hashAlgorithm.toUpperCase());
signer.update(buffer);
return signer.sign(this.options.rsaUtils.exportKey('private'));
}
};
Scheme.prototype.verify = function (buffer, signature, signature_encoding) {
if (this.options.encryptionSchemeOptions && this.options.encryptionSchemeOptions.padding == constants.RSA_NO_PADDING) {
//RSA_NO_PADDING has no verify data
return false;
}
var hashAlgorithm = this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION;
if (this.options.environment === 'browser') {
hashAlgorithm = SIGN_ALG_TO_HASH_ALIASES[hashAlgorithm] || hashAlgorithm;
if (signature_encoding) {
signature = Buffer.from(signature, signature_encoding);
}
var hasher = crypt.createHash(hashAlgorithm);
hasher.update(buffer);
var hash = this.pkcs1pad(hasher.digest(), hashAlgorithm);
var m = this.key.$doPublic(new BigInteger(signature));
return m.toBuffer().toString('hex') == hash.toString('hex');
} else {
var verifier = crypt.createVerify('RSA-' + hashAlgorithm.toUpperCase());
verifier.update(buffer);
return verifier.verify(this.options.rsaUtils.exportKey('public'), signature, signature_encoding);
}
};
/**
* PKCS#1 zero pad input buffer to max data length
* @param hashBuf
* @param hashAlgorithm
* @returns {*}
*/
Scheme.prototype.pkcs0pad = function (buffer) {
var filled = Buffer.alloc(this.key.maxMessageLength - buffer.length);
filled.fill(0);
return Buffer.concat([filled, buffer]);
};
Scheme.prototype.pkcs0unpad = function (buffer) {
var unPad;
if (typeof buffer.lastIndexOf == "function") { //patch for old node version
unPad = buffer.slice(buffer.lastIndexOf('\0') + 1, buffer.length);
} else {
unPad = buffer.slice(String.prototype.lastIndexOf.call(buffer, '\0') + 1, buffer.length);
}
return unPad;
};
/**
* PKCS#1 pad input buffer to max data length
* @param hashBuf
* @param hashAlgorithm
* @returns {*}
*/
Scheme.prototype.pkcs1pad = function (hashBuf, hashAlgorithm) {
var digest = SIGN_INFO_HEAD[hashAlgorithm];
if (!digest) {
throw Error('Unsupported hash algorithm');
}
var data = Buffer.concat([digest, hashBuf]);
if (data.length + 10 > this.key.encryptedDataLength) {
throw Error('Key is too short for signing algorithm (' + hashAlgorithm + ')');
}
var filled = Buffer.alloc(this.key.encryptedDataLength - data.length - 1);
filled.fill(0xff, 0, filled.length - 1);
filled[0] = 1;
filled[filled.length - 1] = 0;
var res = Buffer.concat([filled, data]);
return res;
};
return new Scheme(key, options);
};

183
node_modules/node-rsa/src/schemes/pss.js generated vendored Normal file
View File

@ -0,0 +1,183 @@
/**
* PSS signature scheme
*/
var BigInteger = require('../libs/jsbn');
var crypt = require('crypto');
module.exports = {
isEncryption: false,
isSignature: true
};
var DEFAULT_HASH_FUNCTION = 'sha1';
var DEFAULT_SALT_LENGTH = 20;
module.exports.makeScheme = function (key, options) {
var OAEP = require('./schemes').pkcs1_oaep;
/**
* @param key
* @param options
* options [Object] An object that contains the following keys that specify certain options for encoding.
* └>signingSchemeOptions
* ├>hash [String] Hash function to use when encoding and generating masks. Must be a string accepted by node's crypto.createHash function. (default = "sha1")
* ├>mgf [function] The mask generation function to use when encoding. (default = mgf1SHA1)
* └>sLen [uint] The length of the salt to generate. (default = 20)
* @constructor
*/
function Scheme(key, options) {
this.key = key;
this.options = options;
}
Scheme.prototype.sign = function (buffer) {
var mHash = crypt.createHash(this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION);
mHash.update(buffer);
var encoded = this.emsa_pss_encode(mHash.digest(), this.key.keySize - 1);
return this.key.$doPrivate(new BigInteger(encoded)).toBuffer(this.key.encryptedDataLength);
};
Scheme.prototype.verify = function (buffer, signature, signature_encoding) {
if (signature_encoding) {
signature = Buffer.from(signature, signature_encoding);
}
signature = new BigInteger(signature);
var emLen = Math.ceil((this.key.keySize - 1) / 8);
var m = this.key.$doPublic(signature).toBuffer(emLen);
var mHash = crypt.createHash(this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION);
mHash.update(buffer);
return this.emsa_pss_verify(mHash.digest(), m, this.key.keySize - 1);
};
/*
* https://tools.ietf.org/html/rfc3447#section-9.1.1
*
* mHash [Buffer] Hashed message to encode
* emBits [uint] Maximum length of output in bits. Must be at least 8hLen + 8sLen + 9 (hLen = Hash digest length in bytes | sLen = length of salt in bytes)
* @returns {Buffer} The encoded message
*/
Scheme.prototype.emsa_pss_encode = function (mHash, emBits) {
var hash = this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION;
var mgf = this.options.signingSchemeOptions.mgf || OAEP.eme_oaep_mgf1;
var sLen = this.options.signingSchemeOptions.saltLength || DEFAULT_SALT_LENGTH;
var hLen = OAEP.digestLength[hash];
var emLen = Math.ceil(emBits / 8);
if (emLen < hLen + sLen + 2) {
throw new Error("Output length passed to emBits(" + emBits + ") is too small for the options " +
"specified(" + hash + ", " + sLen + "). To fix this issue increase the value of emBits. (minimum size: " +
(8 * hLen + 8 * sLen + 9) + ")"
);
}
var salt = crypt.randomBytes(sLen);
var Mapostrophe = Buffer.alloc(8 + hLen + sLen);
Mapostrophe.fill(0, 0, 8);
mHash.copy(Mapostrophe, 8);
salt.copy(Mapostrophe, 8 + mHash.length);
var H = crypt.createHash(hash);
H.update(Mapostrophe);
H = H.digest();
var PS = Buffer.alloc(emLen - salt.length - hLen - 2);
PS.fill(0);
var DB = Buffer.alloc(PS.length + 1 + salt.length);
PS.copy(DB);
DB[PS.length] = 0x01;
salt.copy(DB, PS.length + 1);
var dbMask = mgf(H, DB.length, hash);
// XOR DB and dbMask together
var maskedDB = Buffer.alloc(DB.length);
for (var i = 0; i < dbMask.length; i++) {
maskedDB[i] = DB[i] ^ dbMask[i];
}
var bits = 8 * emLen - emBits;
var mask = 255 ^ (255 >> 8 - bits << 8 - bits);
maskedDB[0] = maskedDB[0] & mask;
var EM = Buffer.alloc(maskedDB.length + H.length + 1);
maskedDB.copy(EM, 0);
H.copy(EM, maskedDB.length);
EM[EM.length - 1] = 0xbc;
return EM;
};
/*
* https://tools.ietf.org/html/rfc3447#section-9.1.2
*
* mHash [Buffer] Hashed message
* EM [Buffer] Signature
* emBits [uint] Length of EM in bits. Must be at least 8hLen + 8sLen + 9 to be a valid signature. (hLen = Hash digest length in bytes | sLen = length of salt in bytes)
* @returns {Boolean} True if signature(EM) matches message(M)
*/
Scheme.prototype.emsa_pss_verify = function (mHash, EM, emBits) {
var hash = this.options.signingSchemeOptions.hash || DEFAULT_HASH_FUNCTION;
var mgf = this.options.signingSchemeOptions.mgf || OAEP.eme_oaep_mgf1;
var sLen = this.options.signingSchemeOptions.saltLength || DEFAULT_SALT_LENGTH;
var hLen = OAEP.digestLength[hash];
var emLen = Math.ceil(emBits / 8);
if (emLen < hLen + sLen + 2 || EM[EM.length - 1] != 0xbc) {
return false;
}
var DB = Buffer.alloc(emLen - hLen - 1);
EM.copy(DB, 0, 0, emLen - hLen - 1);
var mask = 0;
for (var i = 0, bits = 8 * emLen - emBits; i < bits; i++) {
mask |= 1 << (7 - i);
}
if ((DB[0] & mask) !== 0) {
return false;
}
var H = EM.slice(emLen - hLen - 1, emLen - 1);
var dbMask = mgf(H, DB.length, hash);
// Unmask DB
for (i = 0; i < DB.length; i++) {
DB[i] ^= dbMask[i];
}
bits = 8 * emLen - emBits;
mask = 255 ^ (255 >> 8 - bits << 8 - bits);
DB[0] = DB[0] & mask;
// Filter out padding
for (i = 0; DB[i] === 0 && i < DB.length; i++);
if (DB[i] != 1) {
return false;
}
var salt = DB.slice(DB.length - sLen);
var Mapostrophe = Buffer.alloc(8 + hLen + sLen);
Mapostrophe.fill(0, 0, 8);
mHash.copy(Mapostrophe, 8);
salt.copy(Mapostrophe, 8 + mHash.length);
var Hapostrophe = crypt.createHash(hash);
Hapostrophe.update(Mapostrophe);
Hapostrophe = Hapostrophe.digest();
return H.toString("hex") === Hapostrophe.toString("hex");
};
return new Scheme(key, options);
};

23
node_modules/node-rsa/src/schemes/schemes.js generated vendored Normal file
View File

@ -0,0 +1,23 @@
module.exports = {
pkcs1: require('./pkcs1'),
pkcs1_oaep: require('./oaep'),
pss: require('./pss'),
/**
* Check if scheme has padding methods
* @param scheme {string}
* @returns {Boolean}
*/
isEncryption: function (scheme) {
return module.exports[scheme] && module.exports[scheme].isEncryption;
},
/**
* Check if scheme has sign/verify methods
* @param scheme {string}
* @returns {Boolean}
*/
isSignature: function (scheme) {
return module.exports[scheme] && module.exports[scheme].isSignature;
}
};

108
node_modules/node-rsa/src/utils.js generated vendored Normal file
View File

@ -0,0 +1,108 @@
/*
* Utils functions
*
*/
var crypt = require('crypto');
/**
* Break string str each maxLen symbols
* @param str
* @param maxLen
* @returns {string}
*/
module.exports.linebrk = function (str, maxLen) {
var res = '';
var i = 0;
while (i + maxLen < str.length) {
res += str.substring(i, i + maxLen) + "\n";
i += maxLen;
}
return res + str.substring(i, str.length);
};
module.exports.detectEnvironment = function () {
if (typeof(window) !== 'undefined' && window && !(process && process.title === 'node')) {
return 'browser';
}
return 'node';
};
/**
* Trying get a 32-bit unsigned integer from the partial buffer
* @param buffer
* @param offset
* @returns {Number}
*/
module.exports.get32IntFromBuffer = function (buffer, offset) {
offset = offset || 0;
var size = 0;
if ((size = buffer.length - offset) > 0) {
if (size >= 4) {
return buffer.readUIntBE(offset, size);
} else {
var res = 0;
for (var i = offset + size, d = 0; i > offset; i--, d += 2) {
res += buffer[i - 1] * Math.pow(16, d);
}
return res;
}
} else {
return NaN;
}
};
module.exports._ = {
isObject: function (value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
},
isString: function (value) {
return typeof value == 'string' || value instanceof String;
},
isNumber: function (value) {
return typeof value == 'number' || !isNaN(parseFloat(value)) && isFinite(value);
},
/**
* Returns copy of `obj` without `removeProp` field.
* @param obj
* @param removeProp
* @returns Object
*/
omit: function (obj, removeProp) {
var newObj = {};
for (var prop in obj) {
if (!obj.hasOwnProperty(prop) || prop === removeProp) {
continue;
}
newObj[prop] = obj[prop];
}
return newObj;
}
};
/**
* Strips everything around the opening and closing lines, including the lines
* themselves.
*/
module.exports.trimSurroundingText = function (data, opening, closing) {
var trimStartIndex = 0;
var trimEndIndex = data.length;
var openingBoundaryIndex = data.indexOf(opening);
if (openingBoundaryIndex >= 0) {
trimStartIndex = openingBoundaryIndex + opening.length;
}
var closingBoundaryIndex = data.indexOf(closing, openingBoundaryIndex);
if (closingBoundaryIndex >= 0) {
trimEndIndex = closingBoundaryIndex;
}
return data.substring(trimStartIndex, trimEndIndex);
}