jsencrypt icon indicating copy to clipboard operation
jsencrypt copied to clipboard

How to use it with nodeJS

Open Norfeldt opened this issue 6 years ago • 10 comments

Tried to make this simple node script

const JSEncrypt = require('JSEncrypt')

const privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCo3cBUt9T1DA4ahjtBrs8RQfGsaL2iibv6y1KB7LhoRzih6x7x
7bbyoEMb7Uqe06+SBKNpEW7jNEAlRftV1DizT6z5EoaV/IwIqdJYGQvN0sXbtsIY
Go8qi8xJiNiN0xBKdUP2EAL3vO5sM6rq45SaApqJMukf6jL4m7z9c+37WwIDAQAB
AoGAXwuJEGXz6ATj/0vkGGEizSzXsNm3Or/ZXRyJkPVDCfZkSsaCwVqx6TgI7bQO
lvzAyifwLdgRGLK1FAWipDlxu5kEMUTH8zLPGT+KC8q7JMRJ6RQegGacmsaVyBiV
/wp6V2GgqFqhzI/nBm/uKQPRFcUNlzBlAFSwo1v4pTTo2TECQQDW07wyUnomSmOU
Zh4bgwLKvkMXC8N8DxL9sxj4SdT2e4LJY5keEeh/OQyZCq1N1UCdyWZnWGaygp5I
5AFMjnupAkEAyTr+iG4vCrqDdFOn/iN6VCatrEwtid/SPipMnvp6F4qu3h2aTryh
77KROeP2a9JP/S9FG3HZTceL3Wgt2uSBYwJBALcpfisVoSnmgPK1AnSIhifggoky
sXCj1ZhTTDXdlWK2OfOFJLa7pBRcyr3tmYdkDBy768CvYZhPv678H5NrZEkCQAld
b38V8aaEK538TrMrH4RPEIIWQYBLJFO0UECN06TI1X6MziOf78FiBBQ3ob4+2W4l
BwhR8hUGlmHFeWzYeZUCQQDTXKBlG2/nPfW6H83gRdlwU+iHtFYY2am/zuOX2s2h
6Tamiy+Fo4VgIafKvifaRwTESSdjIuIVjhAXDKhkq3Ea
-----END RSA PRIVATE KEY-----`

const publicKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCo3cBUt9T1DA4ahjtBrs8RQfGs
aL2iibv6y1KB7LhoRzih6x7x7bbyoEMb7Uqe06+SBKNpEW7jNEAlRftV1DizT6z5
EoaV/IwIqdJYGQvN0sXbtsIYGo8qi8xJiNiN0xBKdUP2EAL3vO5sM6rq45SaApqJ
Mukf6jL4m7z9c+37WwIDAQAB
-----END PUBLIC KEY-----`

// Encrypt with the public key...
var encrypt = new JSEncrypt()
encrypt.setPublicKey(publicKey)
var encrypted = encrypt.encrypt('Hello World')

console.log(encrypted)

// Decrypt with the private key...
var decrypt = new JSEncrypt()
decrypt.setPrivateKey(privateKey)
var uncrypted = decrypt.decrypt(encrypted)

console.log(uncrypted)
const JSEncrypt = require('JSEncrypt')

const privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCo3cBUt9T1DA4ahjtBrs8RQfGsaL2iibv6y1KB7LhoRzih6x7x
7bbyoEMb7Uqe06+SBKNpEW7jNEAlRftV1DizT6z5EoaV/IwIqdJYGQvN0sXbtsIY
Go8qi8xJiNiN0xBKdUP2EAL3vO5sM6rq45SaApqJMukf6jL4m7z9c+37WwIDAQAB
AoGAXwuJEGXz6ATj/0vkGGEizSzXsNm3Or/ZXRyJkPVDCfZkSsaCwVqx6TgI7bQO
lvzAyifwLdgRGLK1FAWipDlxu5kEMUTH8zLPGT+KC8q7JMRJ6RQegGacmsaVyBiV
/wp6V2GgqFqhzI/nBm/uKQPRFcUNlzBlAFSwo1v4pTTo2TECQQDW07wyUnomSmOU
Zh4bgwLKvkMXC8N8DxL9sxj4SdT2e4LJY5keEeh/OQyZCq1N1UCdyWZnWGaygp5I
5AFMjnupAkEAyTr+iG4vCrqDdFOn/iN6VCatrEwtid/SPipMnvp6F4qu3h2aTryh
77KROeP2a9JP/S9FG3HZTceL3Wgt2uSBYwJBALcpfisVoSnmgPK1AnSIhifggoky
sXCj1ZhTTDXdlWK2OfOFJLa7pBRcyr3tmYdkDBy768CvYZhPv678H5NrZEkCQAld
b38V8aaEK538TrMrH4RPEIIWQYBLJFO0UECN06TI1X6MziOf78FiBBQ3ob4+2W4l
BwhR8hUGlmHFeWzYeZUCQQDTXKBlG2/nPfW6H83gRdlwU+iHtFYY2am/zuOX2s2h
6Tamiy+Fo4VgIafKvifaRwTESSdjIuIVjhAXDKhkq3Ea
-----END RSA PRIVATE KEY-----`

const publicKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCo3cBUt9T1DA4ahjtBrs8RQfGs
aL2iibv6y1KB7LhoRzih6x7x7bbyoEMb7Uqe06+SBKNpEW7jNEAlRftV1DizT6z5
EoaV/IwIqdJYGQvN0sXbtsIYGo8qi8xJiNiN0xBKdUP2EAL3vO5sM6rq45SaApqJ
Mukf6jL4m7z9c+37WwIDAQAB
-----END PUBLIC KEY-----`

// Encrypt with the public key...
var encrypt = new JSEncrypt()
encrypt.setPublicKey(publicKey)
var encrypted = encrypt.encrypt('Hello World')

console.log(encrypted)

// Decrypt with the private key...
var decrypt = new JSEncrypt()
decrypt.setPrivateKey(privateKey)
var uncrypted = decrypt.decrypt(encrypted)

console.log(uncrypted)

But I can't get it to work?

▶ node index.js            
/Users/norfeldt/Desktop/AsymEnc/node_modules/JSEncrypt/bin/jsencrypt.js:2624
if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
             ^

ReferenceError: navigator is not defined
    at /Users/norfeldt/Desktop/AsymEnc/node_modules/JSEncrypt/bin/jsencrypt.js:2624:14
    at BI_RM (/Users/norfeldt/Desktop/AsymEnc/node_modules/JSEncrypt/bin/jsencrypt.js:2:65)
    at Object.<anonymous> (/Users/norfeldt/Desktop/AsymEnc/node_modules/JSEncrypt/bin/jsencrypt.js:5:2)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)

Norfeldt avatar Jan 20 '19 18:01 Norfeldt

I used jsencrypt.js on the front end and node-rsa on the node side. . font end:

<body>
    <input type="text" id="content" />
    <button id="start">gogogog</button>
</body>
<script src="/javascripts/jsencrypt.js"></script>
<script>
document.getElementById('start').onclick = function() {
    // 获取公钥
    fetch('/publicKey').then(function(res){
        return res.text();
    }).then(function(publicKey) {
        // 设置公钥并加密
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(publicKey);
        var encrypted = encrypt.encrypt(document.getElementById('content').value);
        // 发送私钥去解密
        fetch('/decryption', {
            method: 'POST',
            body: JSON.stringify({value: encrypted})
        }).then(function(data) {
            return data.text();
        }).then(function(value) {
            console.log(value);
        });
    });
};

backend:

const NodeRSA = require('node-rsa');
const key = new NodeRSA({b: 1024});
// 查看 https://github.com/rzcoder/node-rsa/issues/91
key.setOptions({encryptionScheme: 'pkcs1'});  // 必须加上,加密方式问题。

router.get('/', async (ctx, next) => {
  await ctx.render('index.html')
});

router.get('/publicKey', async (ctx, next) => {
  // 获取公私钥
  var publicDer = key.exportKey('public');
  var privateDer = key.exportKey('private');
  console.log('公钥:',publicDer);
  console.log('私钥:',privateDer);

  ctx.body = publicDer;
});

router.post('/decryption', async (ctx, next) => {
  // 对加密数据进行解密
  var keyValue = JSON.parse(ctx.request.body).value;
  const decrypted = key.decrypt(keyValue, 'utf8');
  console.log('decrypted: ', decrypted);

  ctx.body = decrypted ;
});

or demo.

npm i &  npm run start

port:3000

2fps avatar Feb 21 '19 14:02 2fps

Need to use var keyObj = {key, "padding": crypto.constants.RSA_PKCS1_PADDING}; on node side.

normano avatar Jun 26 '19 01:06 normano

// you can try this, it works global.navigator = {appName: 'nodejs'}; // fake the navigator object global.window = {}; // fake the window object const JSEncrypt = require('jsencrypt').default;

const crypt = new JSEncrypt({default_key_size: 512}); const priveteKey = crypt.getPrivateKey(); const publicKey = crypt.getPublicKey(); console.log(priveteKey, publicKey)

const rawStr = 'hello big star'

const n1cypt = new JSEncrypt(); n1cypt.setPublicKey(publicKey); const encrptStr = n1cypt.encrypt(rawStr);

const n2cypt = new JSEncrypt(); n2cypt.setPrivateKey(priveteKey); const decryptStr = n2cypt.decrypt(encrptStr);

console.log(rawStr, encrptStr, decryptStr);

v4xyz avatar Sep 24 '19 02:09 v4xyz

// you can try this, it works global.navigator = {appName: 'nodejs'}; // fake the navigator object global.window = {}; // fake the window object const JSEncrypt = require('jsencrypt').default;

const crypt = new JSEncrypt({default_key_size: 512}); const priveteKey = crypt.getPrivateKey(); const publicKey = crypt.getPublicKey(); console.log(priveteKey, publicKey)

const rawStr = 'hello big star'

const n1cypt = new JSEncrypt(); n1cypt.setPublicKey(publicKey); const encrptStr = n1cypt.encrypt(rawStr);

const n2cypt = new JSEncrypt(); n2cypt.setPrivateKey(priveteKey); const decryptStr = n2cypt.decrypt(encrptStr);

console.log(rawStr, encrptStr, decryptStr);

This is actually the correct solution.

JiahaoMa0610 avatar Oct 02 '19 17:10 JiahaoMa0610

Thanks @v4xyz It is working

thanhtamha avatar Oct 22 '19 04:10 thanhtamha

// you can try this, it works global.navigator = {appName: 'nodejs'}; // fake the navigator object global.window = {}; // fake the window object const JSEncrypt = require('jsencrypt').default;

const crypt = new JSEncrypt({default_key_size: 512}); const priveteKey = crypt.getPrivateKey(); const publicKey = crypt.getPublicKey(); console.log(priveteKey, publicKey)

const rawStr = 'hello big star'

const n1cypt = new JSEncrypt(); n1cypt.setPublicKey(publicKey); const encrptStr = n1cypt.encrypt(rawStr);

const n2cypt = new JSEncrypt(); n2cypt.setPrivateKey(priveteKey); const decryptStr = n2cypt.decrypt(encrptStr);

console.log(rawStr, encrptStr, decryptStr);

This appears to clash negatively with greenlock - while the node-rsa based solution appears to function correctly at the server side.

chaitanyabd avatar Aug 12 '20 21:08 chaitanyabd

// you can try this, it works global.navigator = {appName: 'nodejs'}; // fake the navigator object global.window = {}; // fake the window object const JSEncrypt = require('jsencrypt').default;

const crypt = new JSEncrypt({default_key_size: 512}); const priveteKey = crypt.getPrivateKey(); const publicKey = crypt.getPublicKey(); console.log(priveteKey, publicKey)

const rawStr = 'hello big star'

const n1cypt = new JSEncrypt(); n1cypt.setPublicKey(publicKey); const encrptStr = n1cypt.encrypt(rawStr);

const n2cypt = new JSEncrypt(); n2cypt.setPrivateKey(priveteKey); const decryptStr = n2cypt.decrypt(encrptStr);

console.log(rawStr, encrptStr, decryptStr);

const crypt = new JSEncrypt({default_key_size: 512});
              ^
TypeError: JSEncrypt is not a constructor

NabiKAZ avatar Apr 17 '22 04:04 NabiKAZ

I resolved it by install nodejs-jsencrypt package instead of jsencrypt:

npm i nodejs-jsencrypt

And then:

const JSEncrypt = require('nodejs-jsencrypt').default;

NabiKAZ avatar Apr 17 '22 04:04 NabiKAZ

@NabiKAZ This can also be resolved by removing the default:

const JSEncrypt = require("jsencrypt"); //note the missing ".default"
let crypt = new JSEncrypt();
// etc.

CoderMuffin avatar Aug 12 '22 15:08 CoderMuffin

I resolved it by install nodejs-jsencrypt package instead of jsencrypt:

npm i nodejs-jsencrypt

And then:

const JSEncrypt = require('nodejs-jsencrypt').default;

God bless you man, God bless you. I gave up twice and came back after some hours and got your comment.

Kamble-Prafful avatar Jan 14 '23 19:01 Kamble-Prafful