From 48e228583723c163affbd8f809ce94e86098477f Mon Sep 17 00:00:00 2001 From: Magnus von Wachenfeldt Date: Thu, 9 Sep 2021 18:52:09 +0200 Subject: [PATCH] remove stuff --- README.md | 377 ------------------------------------------- src/NodeRSA.js | 111 ------------- src/formats/pkcs1.js | 5 - src/formats/pkcs8.js | 5 - src/libs/jsbn.js | 288 +-------------------------------- src/libs/rsa.js | 111 +------------ 6 files changed, 2 insertions(+), 895 deletions(-) diff --git a/README.md b/README.md index e606bb2..e69de29 100644 --- a/README.md +++ b/README.md @@ -1,377 +0,0 @@ -# Node-RSA - -Node.js RSA library
-Based on jsbn library from Tom Wu http://www-cs-students.stanford.edu/~tjw/jsbn/ - -* Pure JavaScript -* No needed OpenSSL -* Generating keys -* Supports long messages for encrypt/decrypt -* Signing and verifying - -## Example - -```javascript -const NodeRSA = require('node-rsa'); -const key = new NodeRSA({b: 512}); - -const text = 'Hello RSA!'; -const encrypted = key.encrypt(text, 'base64'); -console.log('encrypted: ', encrypted); -const decrypted = key.decrypt(encrypted, 'utf8'); -console.log('decrypted: ', decrypted); -``` - -## Installing - -```shell -npm install node-rsa -``` -> Requires nodejs >= 8.11.1 - -### Testing - -```shell -npm test -``` - -## Work environment - -This library developed and tested primary for Node.js, but it still can work in browsers with [browserify](http://browserify.org/). - -## Usage - -### Create instance -```javascript -const NodeRSA = require('node-rsa'); - -const key = new NodeRSA([keyData, [format]], [options]); -``` - -* keyData — `{string|buffer|object}` — parameters for generating key or the key in one of supported formats.
-* format — `{string}` — format for importing key. See more details about formats in [Export/Import](#importexport-keys) section.
-* options — `{object}` — additional settings. - -#### Options -You can specify some options by second/third constructor argument, or over `key.setOptions()` method. - -* environment — working environment (default autodetect): - * `'browser'` — will run pure js implementation of RSA algorithms. - * `'node'` for `nodejs >= 0.10.x or io.js >= 1.x` — provide some native methods like sign/verify and encrypt/decrypt. -* encryptionScheme — padding scheme for encrypt/decrypt. Can be `'pkcs1_oaep'` or `'pkcs1'`. Default `'pkcs1_oaep'`. -* signingScheme — scheme used for signing and verifying. Can be `'pkcs1'` or `'pss'` or 'scheme-hash' format string (eg `'pss-sha1'`). Default `'pkcs1-sha256'`, or, if chosen pss: `'pss-sha1'`. - -> *Notice:* This lib supporting next hash algorithms: `'md5'`, `'ripemd160'`, `'sha1'`, `'sha256'`, `'sha512'` in browser and node environment and additional `'md4'`, `'sha'`, `'sha224'`, `'sha384'` in node only. - -Some [advanced options info](https://github.com/rzcoder/node-rsa/wiki/Advanced-options) - -#### Creating "empty" key -```javascript -const key = new NodeRSA(); -``` - -#### Generate new 512bit-length key -```javascript -const key = new NodeRSA({b: 512}); -``` - -Also you can use next method: - -```javascript -key.generateKeyPair([bits], [exp]); -``` - -* bits — `{int}` — key size in bits. 2048 by default. -* exp — `{int}` — public exponent. 65537 by default. - -#### Load key from PEM string - -```javascript -const key = new NodeRSA('-----BEGIN RSA PRIVATE KEY-----\n'+ - 'MIIBOQIBAAJAVY6quuzCwyOWzymJ7C4zXjeV/232wt2ZgJZ1kHzjI73wnhQ3WQcL\n'+ - 'DFCSoi2lPUW8/zspk0qWvPdtp6Jg5Lu7hwIDAQABAkBEws9mQahZ6r1mq2zEm3D/\n'+ - 'VM9BpV//xtd6p/G+eRCYBT2qshGx42ucdgZCYJptFoW+HEx/jtzWe74yK6jGIkWJ\n'+ - 'AiEAoNAMsPqwWwTyjDZCo9iKvfIQvd3MWnmtFmjiHoPtjx0CIQCIMypAEEkZuQUi\n'+ - 'pMoreJrOlLJWdc0bfhzNAJjxsTv/8wIgQG0ZqI3GubBxu9rBOAM5EoA4VNjXVigJ\n'+ - 'QEEk1jTkp8ECIQCHhsoq90mWM/p9L5cQzLDWkTYoPI49Ji+Iemi2T5MRqwIgQl07\n'+ - 'Es+KCn25OKXR/FJ5fu6A6A+MptABL3r8SEjlpLc=\n'+ - '-----END RSA PRIVATE KEY-----'); -``` - -### Import/Export keys -```javascript -key.importKey(keyData, [format]); -key.exportKey([format]); -``` - -* keyData — `{string|buffer}` — may be: - * key in PEM string - * Buffer containing PEM string - * Buffer containing DER encoded data - * Object contains key components -* format — `{string}` — format id for export/import. - -#### Format string syntax -Format string composed of several parts: `scheme-[key_type]-[output_type]`
- -Scheme — NodeRSA supports multiple format schemes for import/export keys: - - * `'pkcs1'` — public key starts from `'-----BEGIN RSA PUBLIC KEY-----'` header and private key starts from `'-----BEGIN RSA PRIVATE KEY-----'` header - * `'pkcs8'` — public key starts from `'-----BEGIN PUBLIC KEY-----'` header and private key starts from `'-----BEGIN PRIVATE KEY-----'` header - * `'openssh'` — public key starts from `'ssh-rsa'` header and private key starts from `'-----BEGIN OPENSSH PRIVATE KEY-----'` header - * `'components'` — use it for import/export key from/to raw components (see example below). For private key, importing data should contain all private key components, for public key: only public exponent (`e`) and modulus (`n`). All components (except `e`) should be Buffer, `e` could be Buffer or just normal Number. - -Key type — can be `'private'` or `'public'`. Default `'private'`
-Output type — can be: - - * `'pem'` — Base64 encoded string with header and footer. Used by default. - * `'der'` — Binary encoded key data. - -> *Notice:* For import, if *keyData* is PEM string or buffer containing string, you can do not specify format, but if you provide *keyData* as DER you must specify it in format string. - -**Shortcuts and examples** - * `'private'` or `'pkcs1'` or `'pkcs1-private'` == `'pkcs1-private-pem'` — private key encoded in pcks1 scheme as pem string. - * `'public'` or `'pkcs8-public'` == `'pkcs8-public-pem'` — public key encoded in pcks8 scheme as pem string. - * `'pkcs8'` or `'pkcs8-private'` == `'pkcs8-private-pem'` — private key encoded in pcks8 scheme as pem string. - * `'pkcs1-der'` == `'pkcs1-private-der'` — private key encoded in pcks1 scheme as binary buffer. - * `'pkcs8-public-der'` — public key encoded in pcks8 scheme as binary buffer. - -**Code example** - -```javascript -const keyData = '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----'; -key.importKey(keyData, 'pkcs8'); -const publicDer = key.exportKey('pkcs8-public-der'); -const privateDer = key.exportKey('pkcs1-der'); -``` - -```javascript -key.importKey({ - n: Buffer.from('0086fa9ba066685845fc03833a9699c8baefb53cfbf19052a7f10f1eaa30488cec1ceb752bdff2df9fad6c64b3498956e7dbab4035b4823c99a44cc57088a23783', 'hex'), - e: 65537, - d: Buffer.from('5d2f0dd982596ef781affb1cab73a77c46985c6da2aafc252cea3f4546e80f40c0e247d7d9467750ea1321cc5aa638871b3ed96d19dcc124916b0bcb296f35e1', 'hex'), - p: Buffer.from('00c59419db615e56b9805cc45673a32d278917534804171edcf925ab1df203927f', 'hex'), - q: Buffer.from('00aee3f86b66087abc069b8b1736e38ad6af624f7ea80e70b95f4ff2bf77cd90fd', 'hex'), - dmp1: Buffer.from('008112f5a969fcb56f4e3a4c51a60dcdebec157ee4a7376b843487b53844e8ac85', 'hex'), - dmq1: Buffer.from('1a7370470e0f8a4095df40922a430fe498720e03e1f70d257c3ce34202249d21', 'hex'), - coeff: Buffer.from('00b399675e5e81506b729a777cc03026f0b2119853dfc5eb124610c0ab82999e45', 'hex') -}, 'components'); -const publicComponents = key.exportKey('components-public'); -console.log(publicComponents); - -/* -{ n: , - e: 65537 -} -*/ -``` - -If you want to only import the public key use `'components-public'` as an option: - -```javascript -key.importKey({ - n: Buffer.from('0086fa9ba066685845fc03833a9699c8baefb53cfbf19052a7f10f1eaa30488cec1ceb752bdff2df9fad6c64b3498956e7dbab4035b4823c99a44cc57088a23783', 'hex'), - e: 65537, -}, 'components-public'); -``` - -### Properties - -#### Key testing -```javascript -key.isPrivate(); -key.isPublic([strict]); -``` -strict — `{boolean}` — if true method will return false if key pair have private exponent. Default `false`. - -```javascript -key.isEmpty(); -``` -Return `true` if key pair doesn't have any data. - -#### Key info -```javascript -key.getKeySize(); -``` -Return key size in bits. - -```javascript -key.getMaxMessageSize(); -``` -Return max data size for encrypt in bytes. - -### Encrypting/decrypting - -```javascript -key.encrypt(buffer, [encoding], [source_encoding]); -key.encryptPrivate(buffer, [encoding], [source_encoding]); // use private key for encryption -``` -Return encrypted data.
- -* buffer — `{buffer}` — data for encrypting, may be string, Buffer, or any object/array. Arrays and objects will encoded to JSON string first.
-* encoding — `{string}` — encoding for output result, may be `'buffer'`, `'binary'`, `'hex'` or `'base64'`. Default `'buffer'`.
-* source_encoding — `{string}` — source encoding, works only with string buffer. Can take standard Node.js Buffer encodings (hex, utf8, base64, etc). `'utf8'` by default.
- -```javascript -key.decrypt(buffer, [encoding]); -key.decryptPublic(buffer, [encoding]); // use public key for decryption -``` -Return decrypted data.
- -* buffer — `{buffer}` — data for decrypting. Takes Buffer object or base64 encoded string.
-* encoding — `{string}` — encoding for result string. Can also take `'buffer'` for raw Buffer object, or `'json'` for automatic JSON.parse result. Default `'buffer'`. - -> *Notice:* `encryptPrivate` and `decryptPublic` using only pkcs1 padding type 1 (not random) - -### Signing/Verifying -```javascript -key.sign(buffer, [encoding], [source_encoding]); -``` -Return signature for buffer. All the arguments are the same as for `encrypt` method. - -```javascript -key.verify(buffer, signature, [source_encoding], [signature_encoding]) -``` -Return result of check, `true` or `false`.
- -* buffer — `{buffer}` — data for check, same as `encrypt` method.
-* signature — `{string}` — signature for check, result of `sign` method.
-* source_encoding — `{string}` — same as for `encrypt` method.
-* signature_encoding — `{string}` — encoding of given signature. May be `'buffer'`, `'binary'`, `'hex'` or `'base64'`. Default `'buffer'`. - -## Contributing - -Questions, comments, bug reports, and pull requests are all welcome. - -## Changelog - -### 1.1.0 - * Added OpenSSH key format support. - -### 1.0.2 - * Importing keys from PEM now is less dependent on non-key data in files. - -### 1.0.1 - * `importKey()` now returns `this` - -### 1.0.0 - * Using semver now 🎉 - * **Breaking change**: Drop support nodejs < 8.11.1 - * **Possible breaking change**: `new Buffer()` call as deprecated was replaced by `Buffer.from` & `Buffer.alloc`. - * **Possible breaking change**: Drop support for hash scheme `sha` (was removed in node ~10). `sha1`, `sha256` and others still works. - * **Possible breaking change**: Little change in environment detect algorithm. - -### 0.4.2 - * `no padding` scheme will padded data with zeros on all environments. - -### 0.4.1 - * `PKCS1 no padding` scheme support. - -### 0.4.0 - * License changed from BSD to MIT. - * Some changes in internal api. - -### 0.3.3 - * Fixed PSS encode/verify methods with max salt length. - -### 0.3.2 - * Fixed environment detection in web worker. - -### 0.3.0 - * Added import/export from/to raw key components. - * Removed lodash from dependencies. - -### 0.2.30 - * Fixed a issue when the key was generated by 1 bit smaller than specified. It may slow down the generation of large keys. - -### 0.2.24 - * Now used old hash APIs for webpack compatible. - -### 0.2.22 - * `encryptPrivate` and `decryptPublic` now using only pkcs1 (type 1) padding. - -### 0.2.20 - * Added `.encryptPrivate()` and `.decryptPublic()` methods. - * Encrypt/decrypt methods in nodejs 0.12.x and io.js using native implementation (> 40x speed boost). - * Fixed some regex issue causing catastrophic backtracking. - -### 0.2.10 - * **Methods `.exportPrivate()` and `.exportPublic()` was replaced by `.exportKey([format])`.** - * By default `.exportKey()` returns private key as `.exportPrivate()`, if you need public key from `.exportPublic()` you must specify format as `'public'` or `'pkcs8-public-pem'`. - * Method `.importKey(key, [format])` now has second argument. - -### 0.2.0 - * **`.getPublicPEM()` method was renamed to `.exportPublic()`** - * **`.getPrivatePEM()` method was renamed to `.exportPrivate()`** - * **`.loadFromPEM()` method was renamed to `.importKey()`** - * Added PKCS1_OAEP encrypting/decrypting support. - * **PKCS1_OAEP now default scheme, you need to specify 'encryptingScheme' option to 'pkcs1' for compatibility with 0.1.x version of NodeRSA.** - * Added PSS signing/verifying support. - * Signing now supports `'md5'`, `'ripemd160'`, `'sha1'`, `'sha256'`, `'sha512'` hash algorithms in both environments - and additional `'md4'`, `'sha'`, `'sha224'`, `'sha384'` for nodejs env. - * **`options.signingAlgorithm` was renamed to `options.signingScheme`** - * Added `encryptingScheme` option. - * Property `key.options` now mark as private. Added `key.setOptions(options)` method. - - -### 0.1.54 - * Added support for loading PEM key from Buffer (`fs.readFileSync()` output). - * Added `isEmpty()` method. - -### 0.1.52 - * Improve work with not properly trimming PEM strings. - -### 0.1.50 - * Implemented native js signing and verifying for browsers. - * `options.signingAlgorithm` now takes only hash-algorithm name. - * Added `.getKeySize()` and `.getMaxMessageSize()` methods. - * `.loadFromPublicPEM` and `.loadFromPrivatePEM` methods marked as private. - -### 0.1.40 - * Added signing/verifying. - -### 0.1.30 - * Added long message support. - - -## License - -Copyright (c) 2014 rzcoder
- -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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -## Licensing for code used in rsa.js and jsbn.js - -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. - -[![Build Status](https://travis-ci.org/rzcoder/node-rsa.svg?branch=master)](https://travis-ci.org/rzcoder/node-rsa) diff --git a/src/NodeRSA.js b/src/NodeRSA.js index 7cea9d4..92c374d 100644 --- a/src/NodeRSA.js +++ b/src/NodeRSA.js @@ -1,17 +1,9 @@ -/*! - * RSA library for Node.js - * - * Author: rzcoder - * License MIT - */ - var rsa = require('./libs/rsa.js'); var _ = require('./utils')._; var utils = require('./utils'); var schemes = require('./schemes/schemes.js'); var formats = require('./formats/formats.js'); - module.exports = (function () { var SUPPORTED_HASH_ALGORITHMS = { node10: ['md4', 'md5', 'ripemd160', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'], @@ -31,10 +23,6 @@ module.exports = (function () { '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); @@ -71,10 +59,6 @@ module.exports = (function () { this.setOptions(options); } - /** - * Set and validate options for key instance - * @param options - */ NodeRSA.prototype.setOptions = function (options) { options = options || {}; if (options.environment) { @@ -139,13 +123,6 @@ module.exports = (function () { 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; @@ -159,11 +136,6 @@ module.exports = (function () { 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"); @@ -182,10 +154,6 @@ module.exports = (function () { return this; }; - /** - * Exporting key - * @param [format] {string} - */ NodeRSA.prototype.exportKey = function (format) { format = format || DEFAULT_EXPORT_FORMAT; format = EXPORT_FORMAT_ALIASES[format] || format; @@ -197,72 +165,34 @@ module.exports = (function () { 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); @@ -277,9 +207,6 @@ module.exports = (function () { } }; - /** - * Decrypting data method with custom key - */ NodeRSA.prototype.$$decryptKey = function (usePublic, buffer, encoding) { try { buffer = _.isString(buffer) ? Buffer.from(buffer, 'base64') : buffer; @@ -295,14 +222,6 @@ module.exports = (function () { } }; - /** - * 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"); @@ -317,15 +236,6 @@ module.exports = (function () { 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"); @@ -334,29 +244,14 @@ module.exports = (function () { 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'); @@ -369,12 +264,6 @@ module.exports = (function () { } }; - /** - * - * @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'; diff --git a/src/formats/pkcs1.js b/src/formats/pkcs1.js index 5fba246..a6c4893 100644 --- a/src/formats/pkcs1.js +++ b/src/formats/pkcs1.js @@ -126,11 +126,6 @@ module.exports = { ); }, - /** - * 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)) { diff --git a/src/formats/pkcs8.js b/src/formats/pkcs8.js index 3dd1a3c..e5d14a1 100644 --- a/src/formats/pkcs8.js +++ b/src/formats/pkcs8.js @@ -166,11 +166,6 @@ module.exports = { ); }, - /** - * 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); diff --git a/src/libs/jsbn.js b/src/libs/jsbn.js index 5464d7c..dcb230e 100644 --- a/src/libs/jsbn.js +++ b/src/libs/jsbn.js @@ -1,52 +1,8 @@ -/* - * Basic JavaScript BN library - subset useful for RSA encryption. - * - * 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. - */ - -/* - * Added Node.js Buffers support - * 2014 rzcoder - */ - var crypt = require('crypto'); var _ = require('../utils')._; - -// Bits per digit var dbits; - -// JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary & 0xffffff) == 0xefcafe); - -// (public) Constructor function BigInteger(a, b) { if (a != null) { if ("number" == typeof a) { @@ -60,20 +16,9 @@ function BigInteger(a, b) { } } } - -// return new, unset BigInteger function nbi() { return new BigInteger(null); } - -// am: Compute w_j += (x*this_i), propagate carries, -// c is initial carry, returns final carry. -// c < 3*dvalue, x < 2*dvalue, this_i < dvalue -// We need to select the fastest one that works in this environment. - -// am1: use a single mult and divide to get the high bits, -// max digit bits should be 26 because -// max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i, x, w, j, c, n) { while (--n >= 0) { var v = x * this[i++] + w[j] + c; @@ -82,9 +27,6 @@ function am1(i, x, w, j, c, n) { } return c; } -// am2 avoids a big mult-and-extract completely. -// Max digit bits should be <= 30 because we do bitwise ops -// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i, x, w, j, c, n) { var xl = x & 0x7fff, xh = x >> 15; while (--n >= 0) { @@ -97,8 +39,6 @@ function am2(i, x, w, j, c, n) { } return c; } -// Alternately, set max digit bits to 28 since some -// browsers slow down when dealing with 32-bit numbers. function am3(i, x, w, j, c, n) { var xl = x & 0x3fff, xh = x >> 14; while (--n >= 0) { @@ -111,33 +51,15 @@ function am3(i, x, w, j, c, n) { } return c; } - -// We need to select the fastest one that works in this environment. -//if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) { -// BigInteger.prototype.am = am2; -// dbits = 30; -//} else if (j_lm && (navigator.appName != "Netscape")) { -// BigInteger.prototype.am = am1; -// dbits = 26; -//} else { // Mozilla/Netscape seems to prefer am3 -// BigInteger.prototype.am = am3; -// dbits = 28; -//} - -// For node.js, we pick am3 with max dbits to 28. BigInteger.prototype.am = am3; dbits = 28; - BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1 << dbits) - 1); BigInteger.prototype.DV = (1 << dbits); - var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2, BI_FP); BigInteger.prototype.F1 = BI_FP - dbits; BigInteger.prototype.F2 = 2 * dbits - BI_FP; - -// Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = new Array(); var rr, vv; @@ -147,7 +69,6 @@ rr = "a".charCodeAt(0); for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - function int2char(n) { return BI_RM.charAt(n); } @@ -155,15 +76,11 @@ function intAt(s, i) { var c = BI_RC[s.charCodeAt(i)]; return (c == null) ? -1 : c; } - -// (protected) copy this to r function bnpCopyTo(r) { for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } - -// (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x < 0) ? -1 : 0; @@ -171,15 +88,11 @@ function bnpFromInt(x) { else if (x < -1) this[0] = x + DV; else this.t = 0; } - -// return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } - -// (protected) set from string and radix function bnpFromString(data, radix, unsigned) { var k; switch (radix) { @@ -288,20 +201,14 @@ function bnToString(b) { } return m ? r : "0"; } - -// (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; } - -// (public) |this| function bnAbs() { return (this.s < 0) ? this.negate() : this; } - -// (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s - a.s; if (r != 0) return r; @@ -311,8 +218,6 @@ function bnCompareTo(a) { while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; return 0; } - -// returns bit length of the integer x function nbits(x) { var r = 1, t; if ((t = x >>> 16) != 0) { @@ -337,14 +242,10 @@ function nbits(x) { } return r; } - -// (public) return the number of bits in "this" function bnBitLength() { if (this.t <= 0) return 0; return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); } - -// (protected) r = this << n*DB function bnpDLShiftTo(n, r) { var i; for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; @@ -352,15 +253,11 @@ function bnpDLShiftTo(n, r) { r.t = this.t + n; r.s = this.s; } - -// (protected) r = this >> n*DB function bnpDRShiftTo(n, r) { for (var i = n; i < this.t; ++i) r[i - n] = this[i]; r.t = Math.max(this.t - n, 0); r.s = this.s; } - -// (protected) r = this << n function bnpLShiftTo(n, r) { var bs = n % this.DB; var cbs = this.DB - bs; @@ -376,8 +273,6 @@ function bnpLShiftTo(n, r) { r.s = this.s; r.clamp(); } - -// (protected) r = this >> n function bnpRShiftTo(n, r) { r.s = this.s; var ds = Math.floor(n / this.DB); @@ -397,8 +292,6 @@ function bnpRShiftTo(n, r) { r.t = this.t - ds; r.clamp(); } - -// (protected) r = this - a function bnpSubTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { @@ -430,9 +323,6 @@ function bnpSubTo(a, r) { r.t = i; r.clamp(); } - -// (protected) r = this * a, r != this,a (HAC 14.12) -// "this" should be the larger one if appropriate. function bnpMultiplyTo(a, r) { var x = this.abs(), y = a.abs(); var i = x.t; @@ -443,8 +333,6 @@ function bnpMultiplyTo(a, r) { r.clamp(); if (this.s != a.s) BigInteger.ZERO.subTo(r, r); } - -// (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2 * x.t; @@ -460,9 +348,6 @@ function bnpSquareTo(r) { r.s = 0; r.clamp(); } - -// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) -// r != q, this != m. q or r may be null. function bnpDivRemTo(m, q, r) { var pm = m.abs(); if (pm.t <= 0) return; @@ -515,16 +400,12 @@ function bnpDivRemTo(m, q, r) { if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder if (ts < 0) BigInteger.ZERO.subTo(r, r); } - -// (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); return r; } - -// Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } @@ -546,23 +427,11 @@ function cSqrTo(x, r) { x.squareTo(r); this.reduce(r); } - Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; - -// (protected) return "-1/this % 2^DB"; useful for Mont. reduction -// justification: -// xy == 1 (mod m) -// xy = 1+km -// xy(2-xy) = (1+km)(1-km) -// x[y(2-xy)] = 1-k^2m^2 -// x[y(2-xy)] == 1 (mod m^2) -// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 -// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. -// JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if (this.t < 1) return 0; var x = this[0]; @@ -571,14 +440,9 @@ function bnpInvDigit() { y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV return (y > 0) ? this.DV - y : -y; } - -// Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); @@ -587,8 +451,6 @@ function Montgomery(m) { this.um = (1 << (m.DB - 15)) - 1; this.mt2 = 2 * m.t; } - -// xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t, r); @@ -596,27 +458,20 @@ function montConvert(x) { if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); return r; } - -// x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } - -// x = x/R mod m (HAC 14.32) function montReduce(x) { - while (x.t <= this.mt2) // pad x so am has enough room later + while (x.t <= this.mt2) x[x.t++] = 0; for (var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV var j = x[i] & 0x7fff; var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; - // use am to combine the multiply-shift-add into one call j = i + this.m.t; x[j] += this.m.am(0, u0, x, i, 0, this.m.t); - // propagate carry while (x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; @@ -626,31 +481,22 @@ function montReduce(x) { x.drShiftTo(this.m.t, x); if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); } - -// r = "x^2/R mod m"; x != r function montSqrTo(x, r) { x.squareTo(r); this.reduce(r); } - -// r = "xy/R mod m"; x,y != r function montMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); } - Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; - -// (protected) true iff this is even function bnpIsEven() { return ((this.t > 0) ? (this[0] & 1) : this.s) === 0; } - -// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e, z) { if (e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1; @@ -666,31 +512,16 @@ function bnpExp(e, z) { } return z.revert(r); } - -// (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e, m) { var z; if (e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e, z); } - -// Copyright (c) 2005-2009 Tom Wu -// All Rights Reserved. -// See "LICENSE" for details. - -// Extended JavaScript BN functions, required for RSA private ops. - -// Version 1.1: new BigInteger("0", 10) returns "proper" zero -// Version 1.2: square() API, isProbablePrime fix - -//(public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } - -//(public) return value as integer function bnIntValue() { if (this.s < 0) { if (this.t == 1) return this[0] - this.DV; @@ -698,33 +529,22 @@ function bnIntValue() { } else if (this.t == 1) return this[0]; else if (this.t === 0) return 0; -// assumes 16 < DB < 32 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; } - -//(public) return value as byte function bnByteValue() { return (this.t == 0) ? this.s : (this[0] << 24) >> 24; } - -//(public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t == 0) ? this.s : (this[0] << 16) >> 16; } - -//(protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2 * this.DB / Math.log(r)); } - -//(public) 0 if this === 0, 1 if this > 0 function bnSigNum() { if (this.s < 0) return -1; else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; } - -//(protected) convert to radix string function bnpToRadix(b) { if (b == null) b = 10; if (this.signum() === 0 || b < 2 || b > 36) return "0"; @@ -738,8 +558,6 @@ function bnpToRadix(b) { } return z.intValue().toString(b) + r; } - -//(protected) convert from radix string function bnpFromRadix(s, b) { this.fromInt(0); if (b == null) b = 10; @@ -765,8 +583,6 @@ function bnpFromRadix(s, b) { } if (mi) BigInteger.ZERO.subTo(this, this); } - -//(protected) alternate constructor function bnpFromNumber(a, b) { if ("number" == typeof b) { // new BigInteger(int,int,RNG) @@ -794,8 +610,6 @@ function bnpFromNumber(a, b) { this.fromByteArray(x); } } - -//(public) convert to bigendian byte array function bnToByteArray() { var i = this.t, r = new Array(); r[0] = this.s; @@ -822,12 +636,6 @@ function bnToByteArray() { } return r; } - -/** - * return Buffer object - * @param trim {boolean} slice buffer if first element == 0 - * @returns {Buffer} - */ function bnToBuffer(trimOrSize) { var res = Buffer.from(this.toByteArray()); if (trimOrSize === true && res[0] === 0) { @@ -849,7 +657,6 @@ function bnToBuffer(trimOrSize) { } return res; } - function bnEquals(a) { return (this.compareTo(a) == 0); } @@ -859,8 +666,6 @@ function bnMin(a) { function bnMax(a) { return (this.compareTo(a) > 0) ? this : a; } - -//(protected) r = this op a (bitwise) function bnpBitwiseTo(a, op, r) { var i, f, m = Math.min(a.t, this.t); for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); @@ -877,8 +682,6 @@ function bnpBitwiseTo(a, op, r) { r.s = op(this.s, a.s); r.clamp(); } - -//(public) this & a function op_and(x, y) { return x & y; } @@ -887,8 +690,6 @@ function bnAnd(a) { this.bitwiseTo(a, op_and, r); return r; } - -//(public) this | a function op_or(x, y) { return x | y; } @@ -897,8 +698,6 @@ function bnOr(a) { this.bitwiseTo(a, op_or, r); return r; } - -//(public) this ^ a function op_xor(x, y) { return x ^ y; } @@ -907,8 +706,6 @@ function bnXor(a) { this.bitwiseTo(a, op_xor, r); return r; } - -//(public) this & ~a function op_andnot(x, y) { return x & ~y; } @@ -917,8 +714,6 @@ function bnAndNot(a) { this.bitwiseTo(a, op_andnot, r); return r; } - -//(public) ~this function bnNot() { var r = nbi(); for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; @@ -926,22 +721,16 @@ function bnNot() { r.s = ~this.s; return r; } - -//(public) this << n function bnShiftLeft(n) { var r = nbi(); if (n < 0) this.rShiftTo(-n, r); else this.lShiftTo(n, r); return r; } - -//(public) this >> n function bnShiftRight(n) { var r = nbi(); if (n < 0) this.lShiftTo(-n, r); else this.rShiftTo(n, r); return r; } - -//return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if (x === 0) return -1; var r = 0; @@ -964,16 +753,12 @@ function lbit(x) { if ((x & 1) === 0) ++r; return r; } - -//(public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for (var i = 0; i < this.t; ++i) if (this[i] != 0) return i * this.DB + lbit(this[i]); if (this.s < 0) return this.t * this.DB; return -1; } - -//return number of 1 bits in x function cbit(x) { var r = 0; while (x != 0) { @@ -982,44 +767,30 @@ function cbit(x) { } return r; } - -//(public) return number of set bits function bnBitCount() { var r = 0, x = this.s & this.DM; for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); return r; } - -//(public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n / this.DB); if (j >= this.t) return (this.s != 0); return ((this[j] & (1 << (n % this.DB))) != 0); } - -//(protected) this op (1<= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); ++this.t; this.clamp(); } - -//(protected) this += n << w words, this >= 0 function bnpDAddOffset(n, w) { if (n === 0) return; while (this.t <= w) this[this.t++] = 0; @@ -1119,8 +872,6 @@ function bnpDAddOffset(n, w) { ++this[w]; } } - -//A "null" reducer function NullExp() { } function nNop(x) { @@ -1137,14 +888,9 @@ NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; - -//(public) this^e function bnPow(e) { return this.exp(e, new NullExp()); } - -//(protected) r = lower n words of "this * a", a.t <= n -//"this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a, n, r) { var i = Math.min(this.t + a.t, n); r.s = 0; // assumes a,this >= 0 @@ -1155,9 +901,6 @@ function bnpMultiplyLowerTo(a, n, r) { for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); r.clamp(); } - -//(protected) r = "this * a" without lower n words, n > 0 -//"this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a, n, r) { --n; var i = r.t = this.t + a.t - n; @@ -1168,17 +911,13 @@ function bnpMultiplyUpperTo(a, n, r) { r.clamp(); r.drShiftTo(1, r); } - -//Barrett modular reduction function Barrett(m) { -// setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); this.mu = this.r2.divide(m); this.m = m; } - function barrettConvert(x) { if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); else if (x.compareTo(this.m) < 0) return x; @@ -1189,12 +928,9 @@ function barrettConvert(x) { return r; } } - function barrettRevert(x) { return x; } - -//x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t - 1, this.r2); if (x.t > this.m.t + 1) { @@ -1207,26 +943,19 @@ function barrettReduce(x) { x.subTo(this.r2, x); while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); } - -//r = x^2 mod m; x != r function barrettSqrTo(x, r) { x.squareTo(r); this.reduce(r); } - -//r = x*y mod m; x,y != r function barrettMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); } - Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; - -//(public) this^e % m (HAC 14.85) function bnModPow(e, m) { var i = e.bitLength(), k, r = nbv(1), z; if (i <= 0) return r; @@ -1241,8 +970,6 @@ function bnModPow(e, m) { z = new Barrett(m); else z = new Montgomery(m); - -// precomputation var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { @@ -1521,20 +1248,7 @@ BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; BigInteger.int2char = int2char; -// "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); - -// JSBN-specific extension BigInteger.prototype.square = bnSquare; - -//BigInteger interfaces not implemented in jsbn: - -//BigInteger(int signum, byte[] magnitude) -//double doubleValue() -//float floatValue() -//int hashCode() -//long longValue() -//static BigInteger valueOf(long val) - module.exports = BigInteger; \ No newline at end of file diff --git a/src/libs/rsa.js b/src/libs/rsa.js index 158f745..2c34e76 100644 --- a/src/libs/rsa.js +++ b/src/libs/rsa.js @@ -1,44 +1,3 @@ -/* - * 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'); @@ -48,18 +7,6 @@ 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; @@ -85,11 +32,6 @@ module.exports.Key = (function () { 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); @@ -128,18 +70,6 @@ module.exports.Key = (function () { 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); @@ -161,11 +91,6 @@ module.exports.Key = (function () { } }; - /** - * 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); @@ -176,13 +101,6 @@ module.exports.Key = (function () { } }; - /** - * 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); @@ -197,23 +115,11 @@ module.exports.Key = (function () { } 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 = []; @@ -236,11 +142,6 @@ module.exports.Key = (function () { 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'); @@ -268,17 +169,10 @@ module.exports.Key = (function () { 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; }; @@ -301,9 +195,6 @@ module.exports.Key = (function () { } }); - /** - * Caching key data - */ RSAKey.prototype.$$recalculateCache = function () { this.cache = this.cache || {}; // Bit & byte length