Generating a private RSA key for tests (Node.js)

Nikhil Vijayan
1 min readOct 19, 2021

I had this use case of creating a private RSA key that is used only when the tests are run. Since the key doesn’t actually need to be valid (as I use mocks)— I use the following approach. It also helps me not commit a random key to source control.

import { generateKeyPairSync } from 'crypto'export function generatePrivateKeyStub (): string {  const { privateKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
})
return privateKey.export({
format: 'pem',
type: 'pkcs1',
}) as string
}

I’m using the sync method to generate the keys as the tests only run in CI and I don’t mind if this blocks the event loop.

The return type for the privateKey.export function is a string | Buffer union, but actually should be string . I’m fixing this by typecasting it to a string as I return it.

P.S. This is a useful Github gist: https://gist.github.com/keksipurkki/e67b743f1b8174c85712f4fa8b50a065

--

--