You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

377 lines
16 KiB

4 years ago
  1. # Node-RSA
  2. Node.js RSA library<br/>
  3. Based on jsbn library from Tom Wu http://www-cs-students.stanford.edu/~tjw/jsbn/
  4. * Pure JavaScript
  5. * No needed OpenSSL
  6. * Generating keys
  7. * Supports long messages for encrypt/decrypt
  8. * Signing and verifying
  9. ## Example
  10. ```javascript
  11. const NodeRSA = require('node-rsa');
  12. const key = new NodeRSA({b: 512});
  13. const text = 'Hello RSA!';
  14. const encrypted = key.encrypt(text, 'base64');
  15. console.log('encrypted: ', encrypted);
  16. const decrypted = key.decrypt(encrypted, 'utf8');
  17. console.log('decrypted: ', decrypted);
  18. ```
  19. ## Installing
  20. ```shell
  21. npm install node-rsa
  22. ```
  23. > <sub>Requires nodejs >= 8.11.1</sub>
  24. ### Testing
  25. ```shell
  26. npm test
  27. ```
  28. ## Work environment
  29. This library developed and tested primary for Node.js, but it still can work in browsers with [browserify](http://browserify.org/).
  30. ## Usage
  31. ### Create instance
  32. ```javascript
  33. const NodeRSA = require('node-rsa');
  34. const key = new NodeRSA([keyData, [format]], [options]);
  35. ```
  36. * keyData — `{string|buffer|object}` — parameters for generating key or the key in one of supported formats.<br/>
  37. * format — `{string}` — format for importing key. See more details about formats in [Export/Import](#importexport-keys) section.<br/>
  38. * options — `{object}` — additional settings.
  39. #### Options
  40. You can specify some options by second/third constructor argument, or over `key.setOptions()` method.
  41. * environment — working environment (default autodetect):
  42. * `'browser'` — will run pure js implementation of RSA algorithms.
  43. * `'node'` for `nodejs >= 0.10.x or io.js >= 1.x` — provide some native methods like sign/verify and encrypt/decrypt.
  44. * encryptionScheme — padding scheme for encrypt/decrypt. Can be `'pkcs1_oaep'` or `'pkcs1'`. Default `'pkcs1_oaep'`.
  45. * 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'`.
  46. > *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.
  47. <sub>Some [advanced options info](https://github.com/rzcoder/node-rsa/wiki/Advanced-options)</sub>
  48. #### Creating "empty" key
  49. ```javascript
  50. const key = new NodeRSA();
  51. ```
  52. #### Generate new 512bit-length key
  53. ```javascript
  54. const key = new NodeRSA({b: 512});
  55. ```
  56. Also you can use next method:
  57. ```javascript
  58. key.generateKeyPair([bits], [exp]);
  59. ```
  60. * bits — `{int}` — key size in bits. 2048 by default.
  61. * exp — `{int}` — public exponent. 65537 by default.
  62. #### Load key from PEM string
  63. ```javascript
  64. const key = new NodeRSA('-----BEGIN RSA PRIVATE KEY-----\n'+
  65. 'MIIBOQIBAAJAVY6quuzCwyOWzymJ7C4zXjeV/232wt2ZgJZ1kHzjI73wnhQ3WQcL\n'+
  66. 'DFCSoi2lPUW8/zspk0qWvPdtp6Jg5Lu7hwIDAQABAkBEws9mQahZ6r1mq2zEm3D/\n'+
  67. 'VM9BpV//xtd6p/G+eRCYBT2qshGx42ucdgZCYJptFoW+HEx/jtzWe74yK6jGIkWJ\n'+
  68. 'AiEAoNAMsPqwWwTyjDZCo9iKvfIQvd3MWnmtFmjiHoPtjx0CIQCIMypAEEkZuQUi\n'+
  69. 'pMoreJrOlLJWdc0bfhzNAJjxsTv/8wIgQG0ZqI3GubBxu9rBOAM5EoA4VNjXVigJ\n'+
  70. 'QEEk1jTkp8ECIQCHhsoq90mWM/p9L5cQzLDWkTYoPI49Ji+Iemi2T5MRqwIgQl07\n'+
  71. 'Es+KCn25OKXR/FJ5fu6A6A+MptABL3r8SEjlpLc=\n'+
  72. '-----END RSA PRIVATE KEY-----');
  73. ```
  74. ### Import/Export keys
  75. ```javascript
  76. key.importKey(keyData, [format]);
  77. key.exportKey([format]);
  78. ```
  79. * keyData — `{string|buffer}` — may be:
  80. * key in PEM string
  81. * Buffer containing PEM string
  82. * Buffer containing DER encoded data
  83. * Object contains key components
  84. * format — `{string}` — format id for export/import.
  85. #### Format string syntax
  86. Format string composed of several parts: `scheme-[key_type]-[output_type]`<br/>
  87. Scheme — NodeRSA supports multiple format schemes for import/export keys:
  88. * `'pkcs1'` — public key starts from `'-----BEGIN RSA PUBLIC KEY-----'` header and private key starts from `'-----BEGIN RSA PRIVATE KEY-----'` header
  89. * `'pkcs8'` — public key starts from `'-----BEGIN PUBLIC KEY-----'` header and private key starts from `'-----BEGIN PRIVATE KEY-----'` header
  90. * `'openssh'` — public key starts from `'ssh-rsa'` header and private key starts from `'-----BEGIN OPENSSH PRIVATE KEY-----'` header
  91. * `'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.
  92. Key type — can be `'private'` or `'public'`. Default `'private'`<br/>
  93. Output type — can be:
  94. * `'pem'` — Base64 encoded string with header and footer. Used by default.
  95. * `'der'` — Binary encoded key data.
  96. > *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.
  97. **Shortcuts and examples**
  98. * `'private'` or `'pkcs1'` or `'pkcs1-private'` == `'pkcs1-private-pem'` — private key encoded in pcks1 scheme as pem string.
  99. * `'public'` or `'pkcs8-public'` == `'pkcs8-public-pem'` — public key encoded in pcks8 scheme as pem string.
  100. * `'pkcs8'` or `'pkcs8-private'` == `'pkcs8-private-pem'` — private key encoded in pcks8 scheme as pem string.
  101. * `'pkcs1-der'` == `'pkcs1-private-der'` — private key encoded in pcks1 scheme as binary buffer.
  102. * `'pkcs8-public-der'` — public key encoded in pcks8 scheme as binary buffer.
  103. **Code example**
  104. ```javascript
  105. const keyData = '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----';
  106. key.importKey(keyData, 'pkcs8');
  107. const publicDer = key.exportKey('pkcs8-public-der');
  108. const privateDer = key.exportKey('pkcs1-der');
  109. ```
  110. ```javascript
  111. key.importKey({
  112. n: Buffer.from('0086fa9ba066685845fc03833a9699c8baefb53cfbf19052a7f10f1eaa30488cec1ceb752bdff2df9fad6c64b3498956e7dbab4035b4823c99a44cc57088a23783', 'hex'),
  113. e: 65537,
  114. d: Buffer.from('5d2f0dd982596ef781affb1cab73a77c46985c6da2aafc252cea3f4546e80f40c0e247d7d9467750ea1321cc5aa638871b3ed96d19dcc124916b0bcb296f35e1', 'hex'),
  115. p: Buffer.from('00c59419db615e56b9805cc45673a32d278917534804171edcf925ab1df203927f', 'hex'),
  116. q: Buffer.from('00aee3f86b66087abc069b8b1736e38ad6af624f7ea80e70b95f4ff2bf77cd90fd', 'hex'),
  117. dmp1: Buffer.from('008112f5a969fcb56f4e3a4c51a60dcdebec157ee4a7376b843487b53844e8ac85', 'hex'),
  118. dmq1: Buffer.from('1a7370470e0f8a4095df40922a430fe498720e03e1f70d257c3ce34202249d21', 'hex'),
  119. coeff: Buffer.from('00b399675e5e81506b729a777cc03026f0b2119853dfc5eb124610c0ab82999e45', 'hex')
  120. }, 'components');
  121. const publicComponents = key.exportKey('components-public');
  122. console.log(publicComponents);
  123. /*
  124. { 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 ... >,
  125. e: 65537
  126. }
  127. */
  128. ```
  129. If you want to only import the public key use `'components-public'` as an option:
  130. ```javascript
  131. key.importKey({
  132. n: Buffer.from('0086fa9ba066685845fc03833a9699c8baefb53cfbf19052a7f10f1eaa30488cec1ceb752bdff2df9fad6c64b3498956e7dbab4035b4823c99a44cc57088a23783', 'hex'),
  133. e: 65537,
  134. }, 'components-public');
  135. ```
  136. ### Properties
  137. #### Key testing
  138. ```javascript
  139. key.isPrivate();
  140. key.isPublic([strict]);
  141. ```
  142. strict — `{boolean}` — if true method will return false if key pair have private exponent. Default `false`.
  143. ```javascript
  144. key.isEmpty();
  145. ```
  146. Return `true` if key pair doesn't have any data.
  147. #### Key info
  148. ```javascript
  149. key.getKeySize();
  150. ```
  151. Return key size in bits.
  152. ```javascript
  153. key.getMaxMessageSize();
  154. ```
  155. Return max data size for encrypt in bytes.
  156. ### Encrypting/decrypting
  157. ```javascript
  158. key.encrypt(buffer, [encoding], [source_encoding]);
  159. key.encryptPrivate(buffer, [encoding], [source_encoding]); // use private key for encryption
  160. ```
  161. Return encrypted data.<br/>
  162. * buffer — `{buffer}` — data for encrypting, may be string, Buffer, or any object/array. Arrays and objects will encoded to JSON string first.<br/>
  163. * encoding — `{string}` — encoding for output result, may be `'buffer'`, `'binary'`, `'hex'` or `'base64'`. Default `'buffer'`.<br/>
  164. * source_encoding — `{string}` — source encoding, works only with string buffer. Can take standard Node.js Buffer encodings (hex, utf8, base64, etc). `'utf8'` by default.<br/>
  165. ```javascript
  166. key.decrypt(buffer, [encoding]);
  167. key.decryptPublic(buffer, [encoding]); // use public key for decryption
  168. ```
  169. Return decrypted data.<br/>
  170. * buffer — `{buffer}` — data for decrypting. Takes Buffer object or base64 encoded string.<br/>
  171. * encoding — `{string}` — encoding for result string. Can also take `'buffer'` for raw Buffer object, or `'json'` for automatic JSON.parse result. Default `'buffer'`.
  172. > *Notice:* `encryptPrivate` and `decryptPublic` using only pkcs1 padding type 1 (not random)
  173. ### Signing/Verifying
  174. ```javascript
  175. key.sign(buffer, [encoding], [source_encoding]);
  176. ```
  177. Return signature for buffer. All the arguments are the same as for `encrypt` method.
  178. ```javascript
  179. key.verify(buffer, signature, [source_encoding], [signature_encoding])
  180. ```
  181. Return result of check, `true` or `false`.<br/>
  182. * buffer — `{buffer}` — data for check, same as `encrypt` method.<br/>
  183. * signature — `{string}` — signature for check, result of `sign` method.<br/>
  184. * source_encoding — `{string}` — same as for `encrypt` method.<br/>
  185. * signature_encoding — `{string}` — encoding of given signature. May be `'buffer'`, `'binary'`, `'hex'` or `'base64'`. Default `'buffer'`.
  186. ## Contributing
  187. Questions, comments, bug reports, and pull requests are all welcome.
  188. ## Changelog
  189. ### 1.1.0
  190. * Added OpenSSH key format support.
  191. ### 1.0.2
  192. * Importing keys from PEM now is less dependent on non-key data in files.
  193. ### 1.0.1
  194. * `importKey()` now returns `this`
  195. ### 1.0.0
  196. * Using semver now 🎉
  197. * **Breaking change**: Drop support nodejs < 8.11.1
  198. * **Possible breaking change**: `new Buffer()` call as deprecated was replaced by `Buffer.from` & `Buffer.alloc`.
  199. * **Possible breaking change**: Drop support for hash scheme `sha` (was removed in node ~10). `sha1`, `sha256` and others still works.
  200. * **Possible breaking change**: Little change in environment detect algorithm.
  201. ### 0.4.2
  202. * `no padding` scheme will padded data with zeros on all environments.
  203. ### 0.4.1
  204. * `PKCS1 no padding` scheme support.
  205. ### 0.4.0
  206. * License changed from BSD to MIT.
  207. * Some changes in internal api.
  208. ### 0.3.3
  209. * Fixed PSS encode/verify methods with max salt length.
  210. ### 0.3.2
  211. * Fixed environment detection in web worker.
  212. ### 0.3.0
  213. * Added import/export from/to raw key components.
  214. * Removed lodash from dependencies.
  215. ### 0.2.30
  216. * Fixed a issue when the key was generated by 1 bit smaller than specified. It may slow down the generation of large keys.
  217. ### 0.2.24
  218. * Now used old hash APIs for webpack compatible.
  219. ### 0.2.22
  220. * `encryptPrivate` and `decryptPublic` now using only pkcs1 (type 1) padding.
  221. ### 0.2.20
  222. * Added `.encryptPrivate()` and `.decryptPublic()` methods.
  223. * Encrypt/decrypt methods in nodejs 0.12.x and io.js using native implementation (> 40x speed boost).
  224. * Fixed some regex issue causing catastrophic backtracking.
  225. ### 0.2.10
  226. * **Methods `.exportPrivate()` and `.exportPublic()` was replaced by `.exportKey([format])`.**
  227. * 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'`.
  228. * Method `.importKey(key, [format])` now has second argument.
  229. ### 0.2.0
  230. * **`.getPublicPEM()` method was renamed to `.exportPublic()`**
  231. * **`.getPrivatePEM()` method was renamed to `.exportPrivate()`**
  232. * **`.loadFromPEM()` method was renamed to `.importKey()`**
  233. * Added PKCS1_OAEP encrypting/decrypting support.
  234. * **PKCS1_OAEP now default scheme, you need to specify 'encryptingScheme' option to 'pkcs1' for compatibility with 0.1.x version of NodeRSA.**
  235. * Added PSS signing/verifying support.
  236. * Signing now supports `'md5'`, `'ripemd160'`, `'sha1'`, `'sha256'`, `'sha512'` hash algorithms in both environments
  237. and additional `'md4'`, `'sha'`, `'sha224'`, `'sha384'` for nodejs env.
  238. * **`options.signingAlgorithm` was renamed to `options.signingScheme`**
  239. * Added `encryptingScheme` option.
  240. * Property `key.options` now mark as private. Added `key.setOptions(options)` method.
  241. ### 0.1.54
  242. * Added support for loading PEM key from Buffer (`fs.readFileSync()` output).
  243. * Added `isEmpty()` method.
  244. ### 0.1.52
  245. * Improve work with not properly trimming PEM strings.
  246. ### 0.1.50
  247. * Implemented native js signing and verifying for browsers.
  248. * `options.signingAlgorithm` now takes only hash-algorithm name.
  249. * Added `.getKeySize()` and `.getMaxMessageSize()` methods.
  250. * `.loadFromPublicPEM` and `.loadFromPrivatePEM` methods marked as private.
  251. ### 0.1.40
  252. * Added signing/verifying.
  253. ### 0.1.30
  254. * Added long message support.
  255. ## License
  256. Copyright (c) 2014 rzcoder<br/>
  257. 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:
  258. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  259. 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.
  260. ## Licensing for code used in rsa.js and jsbn.js
  261. Copyright (c) 2003-2005 Tom Wu<br/>
  262. All Rights Reserved.
  263. Permission is hereby granted, free of charge, to any person obtaining
  264. a copy of this software and associated documentation files (the
  265. "Software"), to deal in the Software without restriction, including
  266. without limitation the rights to use, copy, modify, merge, publish,
  267. distribute, sublicense, and/or sell copies of the Software, and to
  268. permit persons to whom the Software is furnished to do so, subject to
  269. the following conditions:
  270. The above copyright notice and this permission notice shall be
  271. included in all copies or substantial portions of the Software.
  272. THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
  273. EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
  274. WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
  275. IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
  276. INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
  277. RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
  278. THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
  279. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  280. In addition, the following condition applies:
  281. All redistributions must retain an intact copy of this copyright notice
  282. and disclaimer.
  283. [![Build Status](https://travis-ci.org/rzcoder/node-rsa.svg?branch=master)](https://travis-ci.org/rzcoder/node-rsa)