Deriving Public Keys from Private Keys in JavaScript

This article provides an introduction to deriving public keys from private keys in JavaScript, including the advantages, implementation details, and relevant resources. These steps can help developers improve their efficiency in implementing public key derivation from private keys in JavaScript.

Mar 6, 2022 · 2 min read · 281 Words · -Views -Comments · Programming
JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

I had a requirement to implement public key derivation from private keys in the frontend. After researching several solutions, I finally solved it. Here’s a summary.

Solution

Use node-forge, which supports both browser and Node.js environments, making it suitable for frontend use.

Here’s how to use it in Node.js:

const forge = require('node-forge');// For browser usage, replace with import or directly import the JS module via script tag

const privateKeyPem = fs.readFileSync(`${__dirname}/client1.key`, {
  encoding: 'utf8'
}); // client1 is a PEM format private key file

const forgePriKey = forge.pki.privateKeyFromPem(privateKeyPem);
const forgePubKey = forge.pki.setRsaPublicKey(forgePriKey.n, forgePriKey.e);
const publicKeyPem = forge.pki.publicKeyToPem(forgePubKey);

Other Encryption Approaches

  1. The native frontend crypto API currently has limited functionality and cannot solve this problem
  2. The commonly used community encryption library jsrsasign currently doesn’t support deriving public keys from private keys
  3. The Node.js Crypto module supports crypto.createPublicKey(key), but it can only be used on the server side
  4. The command-line tool openssl supports openssl pkey -in ./client1.key -pubout, but it can only be used on the server side

In summary, if you must implement this in the frontend, you need to use node-forge. If you can leverage server-side implementation, then any of the above solutions will work.

Final Thoughts

I believe there are two main reasons why frontend encryption was historically weak: 1) Limited use cases - the web focused more on interaction than security; 2) Significant performance overhead for encryption/decryption operations. However, with the current development of web technologies, various application scenarios continue to emerge, and hardware improvements have made performance overhead less of an issue. As a result, frontend encryption requirements are becoming increasingly common, putting frontend encryption on the development agenda, as evidenced by the emergence of crypto modules.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover