Code Monkey home page Code Monkey logo

node-rsa's People

Contributors

andrufel94 avatar borup avatar dependabot[bot] avatar dgramop avatar garethsime avatar herrjemand avatar hurryabit avatar maximethoonsen avatar nanov avatar ondralukes avatar pavelvanecek avatar pkinney avatar roblabla avatar rzcoder avatar tehtbl avatar teppeis avatar wheatandtares avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-rsa's Issues

Key Generation 4096 bits in background in NW.js

Hi @rzcoder ! First of all, congratulations for your work! I'm using your node-rsa package in order to generate a RSA 4096 bits(this size is a requirement) key pair in my NW.js. I would like to ask you if you know a node module in order to do this task in background, because when I perform this key generation, all my application is blocked, included the view. What is the best way to face this problem?

Best regards,
Alejandro.

"InvalidAsn1Error" in firefox 48

it works well in firefox 47, but when i tried the latest firefox (version 48) , the browser showed "InvalidAsn1Error". I think the error from "asn1".

Error Cannot find module 'constants' and 'crypto'

I tried to use it on a node project like this :

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

        var rsaKeyData = '-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----';

        var rsaKey = new NodeRSA(rsaKeyData);

        console.log(rsaKey.isPublic());

But some error occured :

Error Cannot find module 'constants'

Error Cannot find module 'crypto'

ReferenceError: Can't find variable: Buffer

So I tried to manually install constants and crypto module , but it still didn't work.

Using webpack and babel :

"dependencies": {
    "babel-runtime": "^6.11.6",
    "crypto-js": "^3.1.6",
    "node-rsa": "^0.4.1",
    "webpack": "^1.13.2"
  },
  "devDependencies": {
    "babel-core": "^6.14.0",
    "babel-loader": "^6.2.5",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-runtime": "^6.12.0",
    "babel-preset-es2015": "^6.14.0",
    "babel-preset-react": "^6.11.1",
    "babel-preset-stage-0": "^6.5.0",
    "babel-preset-stage-1": "^6.13.0",
    "babel-preset-stage-2": "^6.13.0",
    "babel-preset-stage-3": "^6.11.0",
    "json-loader": "^0.5.4"
  }

Is there any solution to this problem?

Thanks.

How to use the keys in c#

Do you have an example on how to import the public key generated by node-rsa in c# and encrypt a message?

In c# we keep getting the message that the key is incorrect, however it works perfekt in nodejs.
We try to create a pcks1-oaep key.

How to load a privatekey that carry password ?

my key:
`-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,D16CD224DF55BFE1

ulcql33AEbE/lHGR6Q16ETE0y/rkTdCSxsCuJs5fQSGqwDgGDSnZPc6GrCREfDkA
1YkKC/EeDwcIH2jZ1p906tfmmBR/bC+Vxy4rqWpUUKQfqnttuND922m250BAQyS/
3xQu/nZRlL/10Uwe5wvy/PJYWQFsMO/BSdcHAu0gLGPiS6auyLo9Kzz8Is/N4tn2
RlsNdQ2kQZTO+jGy58Fb9Wq4S//0VY5a4B2tXVtHcZ5iy7o31uMfrL/FmmEE2sjn
rR4k86FRdZSKZS8Jgj4Q61h2tV4hwf/5SPT4YzEn0v/xFDx2heFad59bj9H92w2P
mrRNOmACSN1lmggcRqwHtH/nixKB/7ZGN+6B5U3tU5K3YBWE/L2oi+l482s13fVg
ju2o9AfSPEtxVy3cLL0zN39UWZa3JOXk8RkFrbE/UZauJJ3fqW45e31CnIdPpcjB
ROkM4GbeneUe0YGqMWUucx3Ddg8U3mz9pqziNbQsQiHgLb0X9xoJ8ucmB+XBx9YZ
DNKm2AX6x6vxg6I74TCF4R20adpmyx2m7EHpZrUB5Zc/Mbyz1SFMDnUSCzTLxLpV
tk6mCNIs/bsBkm4TL9/yHwYllRrGL3CWi+4HUuCmZmlmzqRrtAcVAiHW8hcWiffB
tDsdzxSXfYupcgOU5QerZXGHuV866IrNr0DIbTSE9dEWrwQ6WyxAH2Gy9pEdHpk7
nj6iYOv4rZLOE8UksekIpGbd97CUF7ErCBLB+TTx3kvjd3rcUeXDLI/x9qyXGQmu
N3ZmMzaTrXqnurUZACqVl1DNJA4EuDxONyL1MI37yBFsrhNt9r/b4g==
-----END RSA PRIVATE KEY-----`

My privatekey have a password,
I have tried this, But it's not work:
var privatekey= new NodeRSA(); privatekey.importKey(fs.readFileSync('./key/server.key'), 'pkcs1');

License is ambiguous

Can you improve the license by adding a LICENSE.txt file with the license written out explicitly? It just says "BSD" in the README, which I believe means you intended a BSD license, but what version? It's too ambiguous as is.

Async?

Any plans to create asynchronous versions of encrypt(), decrypt(), etc...?

This looks like a useful lib, but until async versions exist, it's of limited utility w/i Node. I can't block everything else while a key is parsed.

InvalidAsn1Error: Expected 0x2: got 0x30

'use strict';

var fs = require('fs')
var NodeRSA = require('node-rsa');
var key = new NodeRSA('-----BEGIN RSA PRIVATE KEY-----\n'+
'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALQHEIBxMQF4pGlH\n'+
'Nf3IOuBZsWeg58ItDsxXFUJk7GMMTmn5aEL7aAvLM1d1TQzQAR61IJTfxIWm6VCM\n'+
'9w2JYkHn9/p5llbDbAJ7XAlcYCtKUBWITnzbwhnAWAPkHb2LY60A96US2VlUuECe\n'+
'nyMY0ooJi+g7XnGohdNY2jj2OJPNAgMBAAECgYAFv7oBArGtby7/kP9s43GEi5Nf\n'+
'kKMGBOQAQNb+yp6ainXl6snaZbviBd2rBnsXlHw3VlJm3qnLGNRCNxYxRPixvgLk\n'+
'bomCkNvCR13NJM1CPX+OyBRJH/FG6dMawEwtwHqZeA8n3fW0mx1L0v2sIg07OJtj\n'+
'2GgCYzgYBBsGXG5eMQJBAMaxNcPkAlRAbs1PP+Y5vl0IY75jghiU/xwqDRqLySy2\n'+
'tg5yiImCR1myWDSeFu2PsXVA8kV7y+szzQbI2QYy8EUCQQDn87f0wsUB1eoGJyVq\n'+
'MeC8DLiprYIQSr56wDtR981Zo0mEDDmyOkaUq/fAM23bTKOiLuTHXAliQPkGM+Tj\n'+
'ByHpAkEAoL/yfb/U2pEek+CQFBWXm/ETsY8UTAsPspua6mU5p4FTHbEwIgBS9ZDC\n'+
'qB9W8XAV5IVc/TZBLtNEBz8rxkYj+QJBALC36+BsAALdApa7fnMBG1LKcmq8Ccr1\n'+
'11fYW5mgrXBsypbzZYXXhmzA9FoYFMuvAUCQb7c/9NpJ3DCQmwMpLPkCQDK+ln+Q\n'+
'A41Jz/vRtfM7v4U0ojA8uBrnTuol+Y7PecVcQWicNRA34uPS18JT3rBTJQoLfS3y\n'+
'MOKv/gBu3QiWMe8=\n'+
'-----END RSA PRIVATE KEY-----');

var encrypted = 'PNqenCzfKQwImb153wrVgEBbmOKQQSmUnQX98m0uTgg18bWHT/4djGuIo1roZVo8UjfdAGRjPsgjXbGVuhS8mWjm9v+uGPXySEG381fads+rRv/a5b2hMSeIXm3TDFGAe37nDcIkuFHVix5pcxgK9z78aMaKjEdf7U+Yf7QpNbg=';

console.log('Decrypt with Private');
var decrypted = key.decrypt(encrypted, 'utf8');
console.log('decrypted: ', decrypted);

Regex in autoImport suffers from catastrophic backtracking

Using a key that is "copy and pasted" from a text file where "\n" character gets translated to "" and "n" characters, the regex in src/formats/pkcs8.js (and src/formats/pkcs1.js) can hang the node.js process due to (I believe) catastrophic backtracking because of the compounded qualifier in:

/^\s_-----BEGIN RSA PRIVATE KEY-----\s_([A-Za-z0-9+/=]+\s_)+-----END RSA PRIVATE KEY-----\s_$/g

(see http://www.rexegg.com/regex-explosive-quantifiers.html)

Using possessive or atomic grouping would fix the problem but the V8 engine does not support this so we need to emulate it as they suggest here:

http://instanceof.me/post/52245507631/regex-emulate-atomic-grouping-with-lookahead

So a working regex is:

/^s_-----BEGIN RSA PRIVATE KEY-----\s_(?=(([A-Za-z0-9+/=]+\s_)+))\1-----END RSA PRIVATE KEY-----\s_$/g

A test vector to repro the problem is here:

https://gist.github.com/sluggoman/999911c2c5a5436c867a#file-gistfile1-txt

Run with:

node test.js dangerous_bad

And the node process will sit at 100% CPU for a long time.

Interestingly, if you run:

node test.js dangerous_good dangerous_bad

The process doesn't hang (different path in Node's regex code the first time it encounters a regex maybe?)

At any rate, the suggested fix is safer and still properly tests keys.

window undefined in web worker

When using this library in a web worker, the window is undefined, resulting in an error.
I updated the detectEnvironment method in utils.js to do
if (typeof(window) !== 'undefined' && window)
instead of
if (window)
and it fixes the error, but I'm not sure if this results in any wrong behavior.
I will comment on this issue if I find out more.

See also this explaination by MDN:

A worker is an object created using a constructor (e.g. Worker()) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. Thus, using the window shortcut to get the current global scope (instead of self) within a Worker will return an error.

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

Environment detection

While fixing the detection for webpack commit fb40aed breaks the node-detection for nwjs or electron platform, which is a Chromium bundled with nodejs. There node-rsa runs in 'browser' although there is a fully featured node environment... Prior to this commit the environment was correctly identified as 'node'.

From my understanding using the node-implementation is preferred over the pure javascript (eg due to perfomance)

Discerning between public and private keys?

In the following situation, I have a device and server both of which run node and I want to use node-rsa to secure the communication between the two.

Following the example, I would do something like this:

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

var text = 'Hello RSA!';
var encrypted = key.encrypt(text, 'base64');

and then transmit encrypted, however, I can't then decrypt the message, so I should:

  1. (on the server end) generate a key, send only the public key (possibly like var publicDer = key.exportKey('public'); ),
  2. on the client create a new key, by importing the received public key (?)
  3. send the data encrypted with this to the server
  4. decrypt with the original key (?)

Is this correct, and if so, could this (I believe fairly common) procedure be added to the docs? I don't think the info about creating the public/private keys and transferring a public key is shown.

Can't import keys: "encoding too long"

Doing what I think is the simplest test of importing a key:

var rsa = require('node-rsa'); 
var key = new rsa({bits:2048});
var keydata = key.exportKey('pkcs8-public') + '\n' + key.exportKey('pkcs8'); 
var k2 = new rsa(keydata,'pkcs8');

throws an error:

InvalidAsn1Error: encoding too long

Am I doing something obviously wrong?

How do use it in nodejs server and java client?

1.Generate public key and private key then save to database.
2.java client use the public key encrypt the data then use the private key decrypt the data.It is not works.some one help me?
3.error log is here

Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
    at javax.crypto.Cipher.doFinal(Cipher.java:2223)
    at com.cjk.mqtt.RSAUtils.decryptByPrivateKey(RSAUtils.java:161)
    at com.cjk.mqtt.Main.main(Main.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

OpenSSL <--> node-rsa

Hi, I'm trying to implement encryption on iOS and decryption on node. When I read both keys in node, everything works, both with standard padding as with pkcs1, but neither of them decrypts OpenSSL encrypted base64 strings.

The OpenSLL function used is RSA_public_encrypt(chunk_length, plain_chunk, result_chunk, rsa_publicKey, RSA_PKCS1_PADDING)and it outputs a valid base64 string. When trying to decipher it on node-rsa I get:

Error during decryption (probably incorrect key). Original error: Error: Key decrypt method returns null. OpenSLL uses the pem output, the same one I use when testing in node.

Any suggestions?

how can i use a publickey to decrypt?

In order to decrypt by publishkey ,I used to 'openssl_public_decrypt' in php,But in node-rsa,which method should i used?i try import the publish key ,pass verify and then decrypt the source got error.
code:

key = new NodeRSA();
key.importKey(publicKey, 'pkcs8-public');
result = key.verify(source, signBuff);
if (result) {
    var notifydataBuf = new Buffer(notifydata, 'base64')
    var decrypted = key.decrypt(notifydataBuf, 'utf8');
    console.log('decrypted: ', decrypted);
}

And error is:

E:\RSA\node_modules\node-rsa\src\NodeRSA.js:263
throw Error('ErrorOriginal error: ' + e);
^
Error: ErrorOriginal error: TypeError: Cannot call method 'abs' of null
at Error ()
at NodeRSA.module.exports.NodeRSA.decrypt (E:\RSA\node_modules\node->rsa\src\NodeRSA.js:263:19)
at Object. (E:\RSA\RSA.js:195:24)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3

Key length of generated keys too short.

If I generate keys with node-rsa using node.js the key-length does often not match with the specified key.

Minimal example:

rsa = require('node-rsa');
var key = new rsa({b:512});
console.log(key.exportKey());

This results for example in:

-----BEGIN RSA PRIVATE KEY-----
MIIBOAIBAAJAUJcnEo0kWniAhsnSOxCZmpYP0aHOBMPNE0apVyA2WmH7tTpASVHJ
TpKP74irGvDhQX4sp+sEIIXh0Rqwrp+ifQIDAQABAkAyVNRgL6n+nreWdsFHhiyI
cSPcBrPGIgsX+M+VzFZlx4wqPW4WXMs95Q2TLStnxOPg3zYpcAGLUHmFLv1OYdiB
AiEAmoGsZQLnrN3836SojYKCjSePeY5+YdLYEgYe+B3/CY0CIQCFh4FyBjZDWfqU
DtB2h5qzYpQtRbF3PRd4qzG+tfwosQIgS2C6H2mkZ1TBusYVKTyjvoOvXoljJQx9
N4Xe9AOGWj0CICGCFavFf0x7gfQxm4KDGQE3FbQeryAbBo7TdxJCnNqhAiAX1xJA
1uecXytp0QYlMDcMew4DLJxqgNrBL1//5c+UGg==
-----END RSA PRIVATE KEY-----

Saving the generated key to key.pem and invoking:

openssl rsa -in key.pem -text -noout

This gives then the output:

Private-Key: (511 bit)
...

This also happens with higher b-values like 4096. It happens on Mac OSX El capitain and I have seen it also on Windows 7. The gap does not always occur.

If I generate a key with openssl itself:

openssl genrsa -out key.pem 512

the size always matches.

Edit:
The problem does not seem to occur with 2048 bits?

Edit 2:
It also happens with creating an empty key and then invoking generateKeyPair

Uncaught Error: sorry, createSign is not implemented yet

Does that error mean that signing in the browser is out of the question?

The full error is

Uncaught Error: sorry, createSign is not implemented yet
we accept pull requests
http://github.com/dominictarr/crypto-browserify

was trying to sign something in the browser to send to the backend. Can that be done?

public key encryption

I can't see any method to do a public key encryption (encrypting with the public key instead of the private key), which would be needed for e.g. messages where the sender uses the receievrs pubkey to encrypt the message for the receiver only to read.

key.encrypt() seems to use the private key only, am i right?

Output different from ursa

Hi -

I'm attempting to replace my current use of the ursa package with this one, but can't seem to produce the same output.

With some test code like...

var ursa = require('ursa');
var nodersa = require('node-rsa');
var fs = require('fs');

var src = 'largestringoftext'';

var privkey = ursa.createPrivateKey(fs.readFileSync(__dirname + '/../private.key'));
var key1 = privkey.encrypt(src, 'utf8', 'base64').toString('hex');

var privkey = new nodersa(fs.readFileSync(__dirname + '/../private.key'));
var key2 = privkey.encrypt(src, 'base64', 'utf8').toString('hex');

I get different output:

jnHnBLJHT6+uXHQf4WW26qHseKLqI5SOCHapcs8w+H427kU5O515mfdKTgU9bsnfWgbJm9GDiklM8ApnRg17iQB0yXAagTMP6BsiPVD89nwfKr8I6t6s1M2+lcIQnOJ6T1cjWU41Q361E/z5+RpO84jvgOLiuJmIuVk0G6qAHmJ5RMNSK1XZOglOmg6Zz3Pl0tqHeUE+CF2L8j41cGWIcqivVisczLbkX+dXUd6f2XZPK6Z3ivcoCjZfxV+AhKV0lrxw+YvBt3rKOeoiAg0utSnG2Zm9OFPSuNFLJW3mOBRFA4euQNgMwuyqI2z1769rQKmmKXc91nByXyHrJWXfUg==
B9vTCHc+W21Qs+uMjJ8jPcDbo2xZ2PIR//7xV/caJlHo5uwTDa2BAY5yAO4VGJV29cjOl6A1BEyCSFntblkGJBAnM/4euNUV+skNVYFwEJkKZBrz/UOxXl2yV1lxWF3rWHM9yyeMTjLbmqNZZ6Y8iHb6B/0f7T7hPuuDy6YRhXLooKQbArpGKk6JqZtxJ0vmFG2whEfzlJctBWbnbsOUzurODRg/GEMoHXgLQOIcNjwei0Y3Ef8/jfx/PgSQQ/iA+Vi7JAM4cpvvWkq+zDdNRIWmIhn6SeofsfwwAZx07ma8JgZZeEnXyoxE9Y75AoYEtJFpGg5U1Eqr6ryvsiwM5Q==

(where private.key is https://github.com/stephen/nodetunes/blob/master/private.key)

Cleanly separate node and browser versions

Currently, I'm getting an error when bundling via webpack because its trying to bundle io.js . Instead of having a 'brower' environment flag, I propose having a completely separate file that doesn't have any nested reference to file not required by the browser. That way not only will errors like this not happen, but browser bundles using node-rsa will be smaller.

Would you accept a pull request for this?

Use node-rsa in react-native

I have an application developed in react-native platform. I wonder if node-js is compatible with this platform.

TypeError: Cannot call method 'abs' of null

Use RSA Public Key To Decrypty A Private key encrypted string . it raise a error:
TypeError: Cannot call method 'abs' of null
at BigInteger.bnpDivRemTo as divRemTo
at BigInteger.bnMod as mod
at RSAKey.module.exports.Key.RSAKey.$doPrivate (e:\WebstormProjects\XF9_High_Performance_Proxy_Layer\node_modules\node-rsa\src\libs\rsa.js:176:20)
at RSAKey.module.exports.Key.RSAKey.decrypt (e:\WebstormProjects\XF9_High_Performance_Proxy_Layer\node_modules\node-rsa\src\libs\rsa.js:265:26)
at NodeRSA.module.exports.NodeRSA.decrypt (e:\WebstormProjects\prjnode_modules\node-rsa\src\NodeRSA.js:170:52)
at Object. (e:\WebstormProjects\prj\RSAEncrypt.js:51:22)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)

OAEP Support?

Hi there!
I'm attempting to replace ursa with node-rsa, however I've come across an issue where the server will not accept my encrypted data because it apparently only accepts data padded using the OAEP method. I'd like to make a request for this to be added. I'm really not familiar with encryption, nor with this project, but after searching a bit I found this: kjur/jsjws@4a2d895

Perhaps it would be of some help adding OAEP to this great package?
Also, I'm attempting to create a package that implements node-rsa, so I can't really modify the code myself.
I'll attempt my own modifications, if I get anything to work I'll post it to this thread.

DER public key format generation

Hello,

thanks for your library! I am amazed how simple it has been to use, especially as I am a total noob in crypto.

So I successfully generated a private key with your module, but now I need to generate its public key counterpart, in the DER format.
Which is done at the moment with the following system call:

var rsa = spawn("openssl", ["rsa", "-pubout", "-outform", "DER"]);

rsa.stdout.on("data", function(publicKey) {
  // ...
});

rsa.stdin.end(this.privateKey);

Cf. the crx module.

Any idea/suggestion/recommendation?

If I can do that with your module, I simply have not figured out the way to do it.

Thank you in advance :-)

Generates the same key every time

I may be doing something wrong, but under node 0.12:

var generator = new NodeRSA({b: 256});

for (var x = 0; x < 5; x++) {
  key = generator.generateKeyPair();
  console.log(fingerprint(key.exportKey('public'), 'sha1'));

output:

06:f1:22:df:66:55:31:63:96:e4:94:89:86:e8:97:23:82:82:2a:16
06:f1:22:df:66:55:31:63:96:e4:94:89:86:e8:97:23:82:82:2a:16
06:f1:22:df:66:55:31:63:96:e4:94:89:86:e8:97:23:82:82:2a:16
06:f1:22:df:66:55:31:63:96:e4:94:89:86:e8:97:23:82:82:2a:16
06:f1:22:df:66:55:31:63:96:e4:94:89:86:e8:97:23:82:82:2a:16

Problem: "has no method 'copy'" in version 0.2.x

Hello,
I've just update node-rsa from 0.1.54 to 0.2.12. I noticed some modification on APIs, but it still says:

Error during encryption. Original error: TypeError: Object function (dx) { if(isNaN(dx)||dx>this.length){return false;} for(var i=0,n=0;i<this.length;i++) { if(this[i]!=this[dx]) { this[n++]=this[i] } } this.length-=1 return true; } has no method 'copy'

I test it on version 0.2.0 and 0.2.10, this problem still exists, while 0.1.54 is ok.

my test code:

router.get('/rsa',function(req,res){
var key = new nodeRSA({b:2048});
var pri = key.exportKey('private');
var key2 = new nodeRSA(pri);
var text = 'Hello RSA!';
var encrypted = key2.encrypt(text, 'base64');
res.send('aa');
})

and the error:

Error: Error during encryption. Original error: TypeError: Object function (dx)
{
if(isNaN(dx)||dx>this.length){return false;}
for(var i=0,n=0;i<this.length;i++)
{
if(this[i]!=this[dx])
{
this[n++]=this[i]
}
}
this.length-=1
return true;
} has no method 'copy'
at Error ()
at NodeRSA.module.exports.NodeRSA.encrypt (D:\workspace\bakery_web\node_modules\node-rsa\src\NodeRSA.js:239:19)
at module.exports (D:\workspace\bakery_web\routes\test.js:16:23)
at Layer.handle as handle_request
at next (D:\workspace\bakery_web\node_modules\express\lib\router\route.js:100:13)
at Route.dispatch (D:\workspace\bakery_web\node_modules\express\lib\router\route.js:81:3)
at Layer.handle as handle_request
at D:\workspace\bakery_web\node_modules\express\lib\router\index.js:234:24
at Function.proto.process_params (D:\workspace\bakery_web\node_modules\express\lib\router\index.js:312:12)
at D:\workspace\bakery_web\node_modules\express\lib\router\index.js:228:12

Encrypt same string using same key always returns different values

I really don't know what's going on but running the following code gives the odd behavior written in the title:

var someString = 'hello'
var key = new NodeRSA(publicKey,'pkcs8-public-pem')
console.log(key.exportKey('pkcs8-public-pem')) //returns correct key, ok
console.log(key.isPublic()) //returns true, ok
console.log(key.encrypt(someString, 'base64') === key.encrypt(someString, 'base64')) //returns false, NOT OK

That's really really odd!

node version 0.10.25
node-rsa version 0.2.13

v0.2.20 Causing failures in `crx` pkg

After the update to 0.2.20, the crx package was made unusable (at least for my project), providing this error from crx itself:

Error: TypeError: undefined is not a function
  at jenkins-home/workspace/SignalsExtension-Master/node_modules/crx/src/crx.js:83:13
  at $$$internal$$tryCatch (jenkins-home/workspace/SignalsExtension-Master/node_modules/crx/node_modules/es6-promise/dist/es6-promise.js:304:16)
  at $$$internal$$invokeCallback (jenkins-home/workspace/SignalsExtension-Master/node_modules/crx/node_modules/es6-promise/dist/es6-promise.js:316:17)
  at jenkins-home/workspace/SignalsExtension-Master/node_modules/crx/node_modules/es6-promise/dist/es6-promise.js:874:13
  at $$asap$$flush (jenkins-home/workspace/SignalsExtension-Master/node_modules/crx/node_modules/es6-promise/dist/es6-promise.js:111:9)
  at process._tickCallback (node.js:419:13)

Hard-coding the node-rsa dependency in crx to only accept version 0.2.10 of node-rsa consistently fixes the issue.

I have already posted this on CRX, but I wanted to post an issue here to be sure it was noticed by both parties. Unsure yet whether this is because an API method was removed/changed without a major version bump, or because of something else less general.

importKey Asn1Error: Expected 0x30: got 0x2

I'm trying to import a public key:

var key = new NodeRSA();

var testKey = '-----BEGIN PUBLIC KEY-----
MIIBCgKCAQEAmMa/uxBgK32tNSBeHUEDjqeLqPV3Ertu/clp6Pu11Om4KdBaMa5l
p9IVK6MbcttPxWHmxCoizS5yUQaHgrSDNSKLpLJA9sW/3toVYjqMjGNlFuYnpwN+
LeKVSqxJXd4Qfqp3Xr6tQewviejAH854sSBhnEv3xOk33xvVgvR4Nbfn6c9g2WzG
RLjE4l2YyMJaim7RACLapV9+aF+HBrIp8TU/yEEuycYFvHDEX8Edv0oJzsZQzF1K
wexxgHFEiA20uITR4O4m2FNHDDsEDATfT6wboq6Kiyt9lVhadVRAC4F4Ib8rXlFv
zcbo5Zq3Ls479VrdosjJ90R2FiYRYv1wSwIDAQAB
-----END PUBLIC KEY-----';

key.importKey(testKey, 'pkcs8-public');

and I'm getting this on importKey:
InvalidAsn1Error: Expected 0x30: got 0x2

Is there something I'm doing wrong?

How do I verify a signed message?

I'm using node-rsa in Node.js this time (not the browser). I'm not sure how to verify a signed message. Suppose I only have the public PEM, the other end keeps the private PEM private, and send me a signed message. I cannot create a new NodeRSA() with the public PEM.

Code:

// CLIENT CREATES SIGNATURE
var NodeRSA = require("node-rsa");
var clientNodeRsa = new NodeRSA();
clientNodeRsa.generateKeyPair(256);
var signature = clientNodeRsa.sign("hello");

// PRETEND TO PASS DATA FROM CLIENT TO SERVER

// SERVER VERIFIES SIGNATURE
var serverNodeRsa = new NodeRSA();
serverNodeRsa.verify("hello", signature);

It results in

Error: It is not public key

Am I doing it wrong?

Also, if I cheat by giving the server the client private key, the verification result is false:

// client side.
var NodeRSA = require("node-rsa");
var clientNodeRsa = new NodeRSA();
clientNodeRsa.generateKeyPair(256);
var signature = clientNodeRsa.sign("hello");

// server side
var serverNodeRsa = new NodeRSA();
serverNodeRsa.loadFromPEM(clientNodeRsa.getPrivatePEM());
console.log(serverNodeRsa.verify("hello", signature)); // FALSE

Isn't the result supposed to be true?

problem: has no method 'copy'

node-rsa version : 0.2.13
node js version : v0.8.20

code:
var NodeRSA = require('node-rsa');
var key = new NodeRSA({b: 512});

var text = 'Hello RSA!';
var encrypted = key.encrypt(text, 'base64');
console.log('encrypted: ', encrypted);
var decrypted = key.decrypt(encrypted, 'utf8');
console.log('decrypted: ', decrypted);

outPut:
[2015-01-05 17:25:22.364] [ERROR] system - error>>>>>>>>>>>>>>>Error: Error during encryption. Original error: TypeError: Object ?拢卯^2U驴茂耟炉? has no method 'copy'
at Error (unknown source)
at NodeRSA.module.exports.NodeRSA.encrypt (/usr/local/node-v0.6.19/epg-crypt/node_modules/node-rsa/src/NodeRSA.js:239:19)
at test_rsa (/usr/local/node-v0.6.19/epg-crypt/routes/dbSycn.js:86:21)
at dbSycn.rsaTest (/usr/local/node-v0.6.19/epg-crypt/routes/dbSycn.js:39:3)
at callbacks (/usr/local/node-v0.6.19/epg-crypt/node_modules/express/lib/router/index.js:272:11)
at param (/usr/local/node-v0.6.19/epg-crypt/node_modules/express/lib/router/index.js:246:11)
at param (/usr/local/node-v0.6.19/epg-crypt/node_modules/express/lib/router/index.js:243:11)
at pass (/usr/local/node-v0.6.19/epg-crypt/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/usr/local/node-v0.6.19/epg-crypt/node_modules/express/lib/router/index.js:280:5)
at Object.middleware as handle

Encrypting from components incorrect

Unfortunately I am not getting correct results when encrypting based on a given exponent and modulus. The following code is not working and the second snippet is working correctly:

NOT WORKING:

var key = new NodeRSA({
    n: new Buffer(body['publickey_mod'], 'hex'),
    e: body['publickey_exp']
}, 'components', {encryptionScheme: 'pkcs1'});

var encryptedPassword = key.encrypt(password, 'base64', 'utf8');

WORKING:

const NodeRSA = require('node-rsa');
const getPem = require('rsa-pem-from-mod-exp');

var modulus = Buffer(body['publickey_mod'], 'hex').toString('base64');
var exponent = Buffer(body['publickey_exp'], 'hex').toString('base64');
var pem = getPem(modulus, exponent);
var key = new NodeRSA(pem, 'pkcs1-public-pem', {encryptionScheme: 'pkcs1'});
var encryptedPassword = key.encrypt(password, 'base64', 'utf8');

body['publickey_mod'] and body['publickey_exp'] are both HEX.

Could you please tell me why it is not producing correct results? Did I forget something?

PSS padding verification fails when sLen is maximized

When sLen = emLen - hLen - 2, emsa_pss_verify always returns false there.

To reproduce :

var NodeRSA = require('node-rsa');
var key = new NodeRSA({ b: 2048 });

var emLen = Math.ceil((key.keyPair.keySize - 1) / 8);
var hLen = 32; // OAEP.digestLength['sha256'];
var salt_len = emLen - hLen - 2;
key.setOptions({ signingScheme: { scheme: 'pss', hash: 'sha256', saltLength:  salt_len } });

var toSign = new Buffer("test");
var sig = key.sign(toSign);
console.log("Is signature valid ?", key.verify(toSign, sig));

SHA1 signature length

Hi! I'm trying to get an sha-1 signature of a message with a private key.

var client_private = new NodeRSA(require('fs').readFileSync('../providers/sirena/keys/client_private.txt'), {signingAlgorithm: 'sha1'});
message_signature = client_private.sign(message),

And “message_signature” appears to have 256 bytes when simple

openssl dgst -sha1 -binary -out message.signature -sign providers/sirena/keys/client_private.txt message

returns 128 which is required by my provider.

Am I doing something wrong? What should I do to get 128-bytes signature?

Thank you!

What's this InvalidAsn1Error mean?

I'm trying to do key.loadFromPEM(myPrivatePemKey) and it's giving me

Uncaught InvalidAsn1Error: Expected 0x2: got 0x44

The thing is, I have a PEM key string that works just fine, then I put it in a <textarea> by doing $("textarea").text(pemKey), then I get the key back by doing $("textarea").text(), and it stops working. The key value after having put it in the textarea then taking it out seems identical to the naked eye. But obviously something's changed. Is it the newline characters or something?

getting an invalid ASN1 Error

I have a secret which i am attempting to use to generate a new key:

var NodeRSA = require('node-rsa');
var key = new NodeRSA();

var keyData = '-----BEGIN RSA PRIVATE KEY-----PFJTQUtleVZhbHVlPjxNb2R1bHVzPjFvRUl3cmsrY1lDayt4b3BnYTBxM3c5K0l1UWlVZllSZ3dWS1A5dHpOL003WDFnK0NWREJnelExdjVqKzgydGtYYnNpQ2RWc3VoNFdiYWNteUM4Rlgybk51QWVwenhybUtvNEp2OTFYMGc1SnRGZzd5NzNIYlhpcWpVVW1jd1MwZ2dRdGh2bnNZcTBuYkFId0NSSkMxakhIMVRObDFIOVhsVEJpRzVweFVCVT08L01vZHVsdXM+PEV4cG9uZW50PkFRQUI8L0V4cG9uZW50PjwvUlNBS2V5VmFsdWU+-----END RSA PRIVATE KEY-----';
key.importKey(keyData, 'pkcs8');

type=error service=web error="InvalidAsn1Error: encoding too long" stack="InvalidAsn1Error: encoding too long.

I've also gotten the error: expecting x02 but saw x53.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.