rzcoder / node-rsa

Node.js RSA library
1.39k stars 205 forks source link
crypto nodejs rsa signing

Node-RSA

Node.js RSA library
Based on jsbn library from Tom Wu http://www-cs-students.stanford.edu/~tjw/jsbn/

Example

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

npm install node-rsa

Requires nodejs >= 8.11.1

Testing

npm test

Work environment

This library developed and tested primary for Node.js, but it still can work in browsers with browserify.

Usage

Create instance

const NodeRSA = require('node-rsa');

const key = new NodeRSA([keyData, [format]], [options]);

Options

You can specify some options by second/third constructor argument, or over key.setOptions() method.

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

Creating "empty" key

const key = new NodeRSA();

Generate new 512bit-length key

const key = new NodeRSA({b: 512});

Also you can use next method:

key.generateKeyPair([bits], [exp]);

Load key from PEM string

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

key.importKey(keyData, [format]);
key.exportKey([format]);

Format string syntax

Format string composed of several parts: scheme-[key_type]-[output_type]

Scheme — NodeRSA supports multiple format schemes for import/export keys:

Key type — can be 'private' or 'public'. Default 'private'
Output type — can be:

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

Code example

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');
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: <Buffer 00 86 fa 9b a0 66 68 58 45 fc 03 83 3a 96 99 c8 ba ef b5 3c fb f1 90 52 a7 f1 0f 1e aa 30 48 8c ec 1c eb 75 2b df f2 df 9f ad 6c 64 b3 49 89 56 e7 db ... >,
  e: 65537 
}
*/

If you want to only import the public key use 'components-public' as an option:

key.importKey({
    n: Buffer.from('0086fa9ba066685845fc03833a9699c8baefb53cfbf19052a7f10f1eaa30488cec1ceb752bdff2df9fad6c64b3498956e7dbab4035b4823c99a44cc57088a23783', 'hex'),
    e: 65537,
}, 'components-public');

Properties

Key testing

key.isPrivate();
key.isPublic([strict]);

strict — {boolean} — if true method will return false if key pair have private exponent. Default false.

key.isEmpty();

Return true if key pair doesn't have any data.

Key info

key.getKeySize();

Return key size in bits.

key.getMaxMessageSize();

Return max data size for encrypt in bytes.

Encrypting/decrypting

key.encrypt(buffer, [encoding], [source_encoding]);
key.encryptPrivate(buffer, [encoding], [source_encoding]); // use private key for encryption

Return encrypted data.

key.decrypt(buffer, [encoding]);
key.decryptPublic(buffer, [encoding]); // use public key for decryption

Return decrypted data.

Notice: encryptPrivate and decryptPublic using only pkcs1 padding type 1 (not random)

Signing/Verifying

key.sign(buffer, [encoding], [source_encoding]);

Return signature for buffer. All the arguments are the same as for encrypt method.

key.verify(buffer, signature, [source_encoding], [signature_encoding])

Return result of check, true or false.

Contributing

Questions, comments, bug reports, and pull requests are all welcome.

Changelog

1.1.0

1.0.2

1.0.1

1.0.0

0.4.2

0.4.1

0.4.0

0.3.3

0.3.2

0.3.0

0.2.30

0.2.24

0.2.22

0.2.20

0.2.10

0.2.0

0.1.54

0.1.52

0.1.50

0.1.40

0.1.30

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