Deriving Public Keys from Private Keys in JavaScript
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
- The native frontend
crypto
API currently has limited functionality and cannot solve this problem - The commonly used community encryption library
jsrsasign
currently doesn’t support deriving public keys from private keys - The Node.js Crypto module supports
crypto.createPublicKey(key)
, but it can only be used on the server side - The command-line tool
openssl
supportsopenssl 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.