node-jsencrypt icon indicating copy to clipboard operation
node-jsencrypt copied to clipboard

Unable to parse public key

Open akshg05 opened this issue 3 years ago • 2 comments
trafficstars

I am generating a key pair using the npm library keypair. I am able to set the privateKey. However it fails to set the public key with the following error: TypeError: Cannot read property '0' of null ... 4153 | 4154 | // Parse the public key. 4155 | var bit_string = asn1.sub[1];

4156 | var sequence = bit_string.sub[0]; | ^ 4157 | 4158 | modulus = sequence.sub[0].getHexStringValue(); 4159 | this.n = parseBigInt(modulus, 16);

Can you please help?

akshg05 avatar Dec 25 '21 05:12 akshg05

I guess nobody is home :cry:

This code:

import JSEncrypt from 'node-jsencrypt'
import { readFileSync } from 'fs'
import path, { resolve } from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const pubpem = readFileSync(resolve(__dirname, '../ca/server-crt.pem')).toString('utf8')
const keypem = readFileSync(resolve(__dirname, '../ca/server-key.pem')).toString('utf8')

const message = 'Secret message to encrypt'

const encrypt = new JSEncrypt()
encrypt.setPublicKey(pubpem)
const encrypted = encrypt.encrypt(message)


const decrypt = new JSEncrypt()
decrypt.setPrivateKey(keypem)
const uncrypted = decrypt.decrypt(encrypted)

if (message === uncrypted) {
  console.log(`All good: ${message} === ${uncrypted}`)
} else {
  console.error(`Not so good: ${message} !== ${uncrypted}`)
}

Results in:

$ node node-jsencrypt/src/index.js 
/path/to/code/node_modules/node-jsencrypt/index.js:4122
            asn1 = asn1.sub[2].sub[0];
                                  ^

TypeError: Cannot read properties of null (reading '0')
    at RSAKey.parseKey (/path/to/code/node_modules/node-jsencrypt/index.js:4122:35)
    at new JSEncryptRSAKey (/path/to/code/node_modules/node-jsencrypt/index.js:4394:22)
    at JSEncrypt.setKey (/path/to/code/node_modules/node-jsencrypt/index.js:4442:20)
    at JSEncrypt.setPublicKey (/path/to/code/node_modules/node-jsencrypt/index.js:4462:14)
    at file:///path/to/code/node-jsencrypt/src/index.js:23:9
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:530:24)
    at async loadESM (node:internal/process/esm_loader:91:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

trasherdk avatar Nov 26 '22 02:11 trasherdk

Doesn't look like this is maintained.

This should do it: https://github.com/travist/jsencrypt/blob/24e69d8b197b3322d17500af858f3e44e4276f1d/lib/JSEncryptRSAKey.js#L108-L125

ThomasAriano avatar May 10 '23 21:05 ThomasAriano