Node crypto instead of JSEncrypt for encryption with public key - node.js

I have some public key which looks like MIIBIjANBgkqhkiG9w0BAQEFAAO... (392 chars).
It used in the browser to encrypt some strings with JSEncrypt.
How can I encrypt strings with that public key using NodeJS crypto module?
I tried this:
const crypto = require('crypto')
const encrypted = crypto.publicEncrypt('MIIBIjA....', '111111')
console.log(encrypted.toString('base64'))
But got error:0909006C:PEM routines:get_name:no start line.
I also tried to convert the public key and the string into the buffer, got the same error.

If the key in crypto.publicEncrypt(key, buffer) is passed as a string, then it is interpreted as PEM encoded key by default.
A PEM encoded key consists of a header line, followed by the Base64 encoded body (i.e. the Base64 encoded data of the DER encoded key), and a footer line.
In the posted code snippet, the header line is missing (and presumably the footer line as well), which causes the error.
crypto.publicEncrypt(key, buffer) uses OAEP as padding by default. JSEncrypt on the other hand only supports PKCS#1 v1.5 padding. So if the implementation should be compatible to JSEncrypt, i.e. if the ciphertext should be decryptable with JSEncrypt, then PKCS#1 v1.5 padding must be specified explicitly.
The following NodeJS code encrypts a message with the crypto module and decrypts the ciphertext with JSEncrypt:
const crypto = require('crypto')
const { JSEncrypt } = require('js-encrypt')
const publicKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNvs/qUMjkfq2E9o0qn03+KJE7
ASczEbn6q+kkthNBdmTsskikWsykpDPnLWhAVkmjz4alQyqw+mHYP9xhx8qUC4A3
tXY0ObxANUUKhUvR7zNj4vk4t8F2nP3erWvaG8J+sN3Ubr40ZYIYLS6UHYRFrqRD
CDhUtyjwERlz8KhLyQIDAQAB
-----END PUBLIC KEY-----`
const privateKey = `-----BEGIN PRIVATE KEY-----
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAM2+z+pQyOR+rYT2
jSqfTf4okTsBJzMRufqr6SS2E0F2ZOyySKRazKSkM+ctaEBWSaPPhqVDKrD6Ydg/
3GHHypQLgDe1djQ5vEA1RQqFS9HvM2Pi+Ti3wXac/d6ta9obwn6w3dRuvjRlghgt
LpQdhEWupEMIOFS3KPARGXPwqEvJAgMBAAECgYADxGqqL7B9/pPOy3TqQuB6tuNx
4SOGm9x76onqUisoF7LhYqJR4Be/LAKHSR2PkATpKvOcMw6lDvCbtQ+j+rSK2PkN
4iDi1RYqbLUbZBS8vhrgU0CPlmgSSp1NBsqMK9265CaJox3frxmBK1yuf22RboIK
pqOzcluuA4aqLegmwQJBAP0+gM/tePzx+53DrxpYQvlfi9UJo7KeqIFL8TjMziKt
EaRGeOZ6UX/r6CQHojYKnNti7pjAwonsdwCTcv1yy7sCQQDP+/ww49VFHErON/MO
w5iYCsrM5Lx+Yc2JAjetCDpkMrRT92cgQ0nxR5+jNeh+gE2AmB9iKlNxsHJoRaPQ
lBRLAkEAl9hiZEp/wStXM8GhvKovfldMAPFGtlNrthtTCDvFXgVoDpgy5f9x3sIU
74WkPcMfSmyHpA/wlcKzmCTRTicHAQJBALUjq7MQ2tAEIgqUo/W52I6i55mnpZsU
pyOqcL8cqW5W0sNGd+SbdizTym8lJkX2jIlw8/RVFLOxjxLNhCzGqx0CQQDeUMnw
7KGP3F7BnbsXCp64YDdihzSO5X/Mfwxw6+S/pyKZ0/X4uwt24kZuoDnFzGWJYlea
sDQC6enIru+ne5es
-----END PRIVATE KEY-----`
// Encrypt with crypto module (RSA - PKCS#1 v1.5 Padding)
var ciphertext = crypto.publicEncrypt(
{
key: publicKey,
padding: crypto.constants.RSA_PKCS1_PADDING
},
Buffer.from('The quick brown fox jumps over the lazy dog','utf8')
)
console.log(ciphertext.toString('base64'))
// Decrypt with JSEncrypt
var decrypt = new JSEncrypt()
decrypt.setPrivateKey(privateKey)
var decrypted = decrypt.decrypt(ciphertext.toString('base64'))
console.log(decrypted) // The quick brown fox jumps over the lazy dog

Related

Reading public and private key from stored files in node js

I wanted to encrypt and decrypt a message in node using public and private keys stored in my system. I was using the following java code to read the file and use the keys.
Java Code:
byte[] keyBytes = Files.readAllBytes(new File(publicKeyFileName).toPath());
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
publicKey=kf.generatePublic(spec);
I am able to use the above java method without any issues to read the public key from file. However, I want to achieve similar functionality in node.
I have tried using crypto for achieving the same but it gives me error while passing the key to publicEncrypt method.
Node:
var encryptStringWithRsaPublicKey = function(toEncrypt, relativeOrAbsolutePathToPublicKey) {
var absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey);
var publicKey = fs.read(absolutepath, "utf-8");
console.log(publicKey);
var buffer = Buffer.from(toEncrypt);
var encrypted = crypto.publicEncrypt(publicKey, buffer);
return encrypted.toString("base64");
};
Error
internal/crypto/cipher.js:43
return method(toBuf(key), buffer, padding, passphrase);
^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
Please help. Thanks
Your problem is located in the file format you are actually using with Java. You probably save the
private and the public in encoded ("byte array") to a file and rebuild the keys e.g. with
X509EncodedKeySpec.
This format is not compatible to Node.JS and you have 3 ways to solve it:
a) you write the keys in Java with re neccessary format for usage in Node.JS
b) you write a converter in Node.JS to get the correct format
c) you convert the files with a tool like OPENSSL.
Here I show you the "c-way" as you are handling just one keypair and probably don't need a programatically solution.
Let's say you have two files with the private key ("rsa_privatekey_2048.der") and the public key ("rsa_publickey_2048.der").
In OPENSSL you are using the command line with
openssl rsa -inform der -in rsa_privatekey_2048.der -outform pem -out rsa_privatekey_2048.pem
openssl rsa -inform der -pubin -in rsa_publickey_2048.der -outform pem -RSAPublicKey_out -out rsa_publickey_2048.pem
to convert the files to their PEM-encoded formats.
Below you can find the two sample files I created.
rsa_privatekey_2048.pem:
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAmbeKgSAwVe0nZ84XlbDhMkUDjx1C0duA16MkzHTg1uh9SouO
KK0e3gPtTJ9LssaHlXSYhjpMDMWGO6ujd85XRosI2u9eSMNRYY25AQuBriSTVdi9
BHqWAuWuo6VuvTrkgWTL69vNWvLXTOkTiIyrgnhiavjNvm4UVy2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h74Mu/cAzdgPUCgYEAiNANdwt29AKyUyefykpLGCczGL8aPP88l6z7
R38uAX1Ygg/pdJoUrnHo+FkIbHkcXMRfHFF3j7NoMWynwSLg50OUiPX80SiLN5qm
iytDzskZjsEL2gq6IF1NHRabTfWlmrVDjR9mQhTabq+NtIDwlPOqs9100nrlbFIy
6uU0z18CgYEAkDxQg5UjOzbYIighp/e0LkfKlwUE/cMtISUq1A6Yio9AKZYdBV8p
dd4osUW0gZvDflXlQaBIaNlOwl035lyEZtyuKmFh1oSmoir/TTMbIk0avSgKCLGg
fnhabaQRHl4RdXWcEsioRv3aZUsGkb46Y8xODyAUPRHBPhBsd71gnZ8=
-----END RSA PRIVATE KEY-----
rsa_publickey_2048.pem:
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAmbeKgSAwVe0nZ84XlbDhMkUDjx1C0duA16MkzHTg1uh9SouOKK0e
3gPtTJ9LssaHlXSYhjpMDMWGO6ujd85XRosI2u9eSMNRYY25AQuBriSTVdi9BHqW
AuWuo6VuvTrkgWTL69vNWvLXTOkTiIyrgnhiavjNvm4UVy2AcO2Y3ER+dKgJpQAY
lEP1jvuQuf6dfNdSBoN0DZbxZXYbQqoA9R/u0GZHCXY+r8A54RejG34pnnuHkoyR
OZz5H9LbKGOiaETryornQ1TRvB/p9tgIoCJFI71WsKsqeWQPG3Ymg/FoEWXNY0yo
pZEjpkZa3tU+hrOmAFIRg+/bedKfjYFi/QIDAQAB
-----END RSA PUBLIC KEY-----
There's potentially a few issues with your code or the encryption key you're using:
You're using fs.read incorrectly as Node is asynchronous and it needs a callback function to properly read the file.
The encryption key you're using is formatted incorrectly for crypto.publicEncrypt. You must have the proper RSA headers.
I modified your code to use fs.readFile properly instead in the standard Node callback form, and here's an example encryption key in the correct RSA format to use:
var path = require('path');
var crypto = require('crypto');
var fs = require('fs');
var encryptStringWithRsaPublicKey = function(toEncrypt, relativeOrAbsolutePathToPublicKey, callback) {
var absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey);
fs.readFile(absolutePath, 'utf-8', (err, publicKey) => {
// The value of `publicKey` is in the callback, not the return value
console.log(publicKey);
var buffer = Buffer.from(toEncrypt);
var encrypted = crypto.publicEncrypt(publicKey, buffer);
if (err) {
callback(err);
} else {
callback(null, encrypted.toString("base64"));
}
});
};
encryptStringWithRsaPublicKey('hello world', 'test.pub', (err, encrypted) => {
// If you're using a callback in a function,
// the original function must have a callback as well
console.log(encrypted);
});
Example encryption key at test.pub (must have the RSA headers as shown below):
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEA+xGZ/wcz9ugFpP07Nspo6U17l0YhFiFpxxU4pTk3Lifz9R3zsIsu
ERwta7+fWIfxOo208ett/jhskiVodSEt3QBGh4XBipyWopKwZ93HHaDVZAALi/2A
+xTBtWdEo7XGUujKDvC2/aZKukfjpOiUI8AhLAfjmlcD/UZ1QPh0mHsglRNCmpCw
mwSXA9VNmhz+PiB+Dml4WWnKW/VHo2ujTXxq7+efMU4H2fny3Se3KYOsFPFGZ1TN
QSYlFuShWrHPtiLmUdPoP6CV2mML1tk+l7DIIqXrQhLUKDACeM5roMx0kLhUWB8P
+0uj1CNlNN4JRZlC7xFfqiMbFRU9Z4N6YwIDAQAB
-----END RSA PUBLIC KEY-----
As of 2020, there are also other ways of making the code cleaner, such as with using the Promises version of the fs module and async / await, though I wanted to keep this answer as simple as possible for now.

How to generate a PEM-formatted Key from a 64Byte raw hex-formatted Key

I have the following problem:
After recreating the public key from a signed transaction, I try to encrypt some payload with it.
However the node.js-module named "crypto" is expecting a pem-formatted key in the publicEncrypt(key, payload) function.
My Question:
How can I create the pem-formatted key from a raw hex-encoded key?
Here is the recreated 64 Byte public key:
9f9f445051e788461952124dc08647035c0b31d51f6b4653485723f04c9837adb275d41731309f6125c14ea1546d86a27158eec4164c00bab4724eed925e9c60
Information:
I know, that a pem-format-key consists of base64 encoded data, a header and a footer.
-----BEGIN RSA PUBLIC KEY-----
BASE64 ENCODED DATA
-----END RSA PUBLIC KEY-----
I have also found out that within the base64 encoded data the following DER-structure is present:
RSAPublicKey ::= SEQUENCE {
modulus INTEGER, -- n
publicExponent INTEGER -- e
}
So the only question is how to get from the raw hex-encoded key to this DER-structure.
I would appreciate any help!
Problem solved
Thanks to Maarten Bodewes and his comment regarding the key being secp256k1 and not RSA.
After some further research, I finally managed to encrypt/decrypt a message asymmetrically with secp256k1 keys.
With the help of Cryptos ECDH class I managed to create a key-object and then assign the private key to it. When assigned, you can easily derive the public key with getPublicKey(). All participants would create a key object for themselves and assign their private keys to it. Then they share their retrieved public keys (in my case over a shared medium). In addition I used a npm-package named standard-ecies which provides the ECIES encryption-scheme.
Code:
const crypto = require('crypto');
const ecies = require('standard-ecies');
var buffer = new Buffer("Hello World");
var ecdh = crypto.createECDH('secp256k1');
ecdh.setPrivateKey(privateKey);
var encryptedText = ecies.encrypt(ecdh.getPublicKey(), buffer);
var decryptedText = new Buffer(ecies.decrypt(ecdh, encryptedText));
I should have noticed this, because crypto's encryption function (link to the api-doc) clearly works only with RSA keys and not with secp256k1 keys.
Anyway if someone has a similar issue, I hope this answer helps!

OpenSSL Node.js Error No Start Line

I started developing an app in node.js for the german Sparkasse (banking provider).
They provide an API to their service.
German Link to their API
in the secondstep I get a RSA-2048-SHA1 publickey from their server.
in the fourth step, I should use that public key, to encrypt a session key created in step 3. but when encrypting with:
var key = 'password';
var sha256 = crypto.createHash('sha256');
sha256.update(key);
var iv = new Buffer([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);
var cipher = crypto.createCipheriv('aes-256-cbc', sha256.digest(), iv);
let sessionKey = cipher.final('base64')
let publicKey = response.publicKey.value
crypto.publicEncrypt(publicKey,new Buffer(sessionKey))
I get the following Error message, that I think is from OpenSSL. I don't really know how to fix that issue as I cannot evaluate if the publicKey I get from the API is valid.
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
The public key you received is in the wrong format. It needs to be a "PEM" formatted key. You'll have to convert it by wrapping it in "BEGIN ..." and "END..." lines, and possibly splitting into 64 character lines.
Here is an example of a properly formatted public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAytBCDJR5/6JAlB7ErBge
22YwN/u0K63wrnCMLde+hQQCYs7pBuYtbyxXF2PBFuHS+ytD9PSpY9t3NiGbk/9U
s9GYCnqaK+vg2hz+T86LjJVkTJe0HWuE6g+HQ9GjyDGiO7ZBQw31HKxHYA2cMMVj
tiO97VKLR9Fp6c6X33uNtdAaUZg57PjyNl6TjPwc52tJz8H5g0aV4tYelsTMaSSE
4nVwPLBoDzZaT84ktW1RuGToC4gEB/bctFrRBVaxp/KSebpds9P2xGMVweWgrvml
cLnHGLKBxcCxh9kbgHS/nrgYXPjj92hxk2se/C7QmYeRSUs4ikEWO06NJ7Cgk+bQ
8wIDAQAB
-----END PUBLIC KEY-----
on each new line start you shuould put : /n
if you keep it as string on config file , on windows you should save it like that:
"JWTPRIVATE": "-----BEGIN RSA PRIVATE KEY-----\nMIIJKAIBAAKCA...
just to show you how it looks before i deleted the spaces:
"-----BEGIN PUBLIC KEY-----/n
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAytBCDJR5/6JAlB7ErBge/n
22YwN/u0K63wrnCMLde+hQQCYs7pBuYtbyxXF2PBFuHS+ytD9PSpY9t3NiGbk/9U/n
..."
for new line as you can see here: Why does "\n" give a new line on Windows?

node-forge how to read a private rsa key from file

This question is related to Issue using RSA encryption in javascript
I have a node script that I am trying to read a PEM RSA private key from a file:
const forge = require('node-forge');
const fs = require('fs');
const path = require('path');
let pkey = fs.readFileSync(path.join(__dirname, 'test.key'), 'utf8');
//let pkeyDer = forge.util.decode64(pkey); // since it's not base64 encoded, i suppose don't need to decode
let pkeyAsn1 = forge.asn1.fromDer(pkey);
let privateKey = forge.pki.privateKeyFromAsn1(pkeyAsn1);
The test.key file has a format like this:
-----BEGIN RSA PRIVATE KEY-----
{mumbo jumbo line1}
{mumbo jumbo line2}
...
-----END RSA PRIVATE KEY-----
When I tried to import the file, the line fails at pkeyAsn1 = forge.asn1.fromDer(pkey);, giving this error:
Too few bytes to read ASN.1 value.
I don't know too much about the file format, would somebody help me?
The private key file i generated is using the following openssl command:
openssl rsa -in encrypted_test.key -out test.key and I entered my passphrase to decrypt such rsa key.
Read pkey as bytes and use forge.pki.privateKeyFromPem.
Working code:
const forge = require('node-forge');
const fs = require('fs');
const path = require('path');
let pkey = fs.readFileSync(path.join(__dirname, 'test.key'));
let privateKey = forge.pki.privateKeyFromPem(pkey);
I think i figured it out. When reading a private key file, you must include the ---BEGIN RSA PRIVATE KEY--- and ---END RSA PRIVATE KEY--- banner.

NodeRSA key header and footer

I am using Node.js RSA library (https://github.com/rzcoder/node-rsa) to generate a public and private key pair with the following codes:
const key = new nodeRSA();
key.generateKeyPair(2048, 65537);
const pemPublicKey = key.exportKey('pkcs1-public-pem');
const pemPrivateKey = key.exportKey('pkcs1-private-pem');
The key I get is as follows:
-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAnvrbDfGOT9pmKWZafkEizt8WfMbhmf46e7zyHMRQNHTxPKuP89fc\n5BAkhXylC9ozfjTjiQb5wDh1yw5HafyAKE4Jh28fzX1TJnVra1ijpQTte4+v1WVe\na8qxBuzUI6bxJtR/AV1XyfeWbYx27lSenw2ynqiut+oQ5MZ9kOxX4ba+/cWYcvMn\ni0OnhnNIQp0a+cY78sfz/LpDMumWDVZKvOTREg1y9KxGkd/yyYrHyxAAsfijY/47\n70KH0c4FjjYrWipVHAHj/ayhoAFRBFY9uI9pqLamf8AfBsjvIT16/viT4LE6kUEu\nU2zxOUevkjTq3tgOZoFomiSDJC1EopVhvQIDAQAB\n-----END RSA PUBLIC KEY-----
Question is: how can I get rid of the header and footer and the \n in the base64 string?
The reason I want to do it is just because I wanna the key to be consistent with what I have in the database
Thanks!
According to Import/Export documentation you can export the key as DER and convert the result to base64. (PEM is DER binary format converted to base64 and adding header and footer)
const derPublicKey = key.exportKey('pkcs1-public-der');
const derPrivateKey = key.exportKey('pkcs1-private-der');
I'm not familiar with node.js. Converting binary to base64 should look something like this
var derB64PublicKey = new Buffer(derPublicKey , 'binary').toString('base64');
var derB64PrivateKey = new Buffer(derPrivateKey , 'binary').toString('base64');
Alternatively it would be easy to delete header, footer and \n from the PEM data, but the option to export to DER seems more reasonable

Resources