intA
intA

Reputation: 2701

Using the Node crypto library for some simple private key encryption but getting errors

I'm putting together a quick POC to encrypt an incoming string using a common key. This is what I have in my middleware:

import Crypto from 'crypto';

export default async function encrypt(req, res) {
  try {
    let aesKey = "thisisouraestestkey";

    let toEncrypt = req.body.encryptString;
    let buf = Buffer.from(toEncrypt, 'utf8');
    let encryptedString = Crypto.privateEncrypt(aesKey, buf);

    res.status(200).json({ encryptedString });
  }
  catch(err) {
    logger.error(`there was an error: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
}

I am getting the following error when trying to encrypt:

there was an error: error:0906D06C:PEM routines:PEM_read_bio:no start line

After doing a bit of seraching on this error I see a lot of mentions of my local certificate files. I'm not sure why it would be using any local certificates or anything like that. I want this encryption to run the same no matter what machine it is running on so I wouldn't want it to depend on local files.

I'm currently running the project locally but it will be built and deployed to a remote machine.

Upvotes: 0

Views: 443

Answers (1)

Artjom B.
Artjom B.

Reputation: 61952

crypto#privateEncrypt expects an RSA private key in order to "encrypt" with a private key. Note that such a thing is usually called "signing" when proper hashing is performed. So crypto#privateEncrypt is a low-level primitive to implement your own RSA signing operation. crypto#publicDecrypt would be the low-level primitive to implement RSA verification. That's probably too low-level for you. Don't roll your own crypto!

Since your key is short and contains "aes" in a variable name, I suspect you're looking for symmetric encryption or secret-key encryption using AES. crypto.createCipheriv and the Cipher object are your friends for this use case. Note that you have to think about the mode of operation and possibly the padding scheme. I suggest AES-256-GCM as seen in this implementation.

Upvotes: 2

Related Questions