Using private key in a .env file

Solution which worked for me -- Encoding the Private Key in base 64

Step1 - Convert Key to Base 64

// Run this code in a JS file on your Dev Machine.
const privateKey= `-----BEGIN PRIVATE KEY-----\nMIIEvSomeMoreCharacterHererplw==\n-----END PRIVATE KEY-----\n`
const buff = Buffer.from(privateKey).toString('base64');
console.log(buff);

Note: You don't need to commit/include the above code in your project. This is just to generate the base64 string of the key.

Step 2 - Copy the console log data to .env file

PRIVATE_KEY = 'akgjhakdgjhasgf'

Step 3 - Using the Key in the code

const key = Buffer.from(process.env.PRIVATE_KEY , 'base64').toString('ascii');
// Use key anywhere in your code.

I'm adding a manual approach that worked for me. Step 1:

echo "PRIVATE_KEY=\"`sed -E 's/$/\\\n/g' my_rsa_2048_priv.pem`\"" >> .env

Your key in the .env file will look something like this:

PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\n
dasdasdadasdasdasdasdasdasdasdadasdasdadasa\n
huehuauhhuauhahuauhauahuauhehuehuauheuhahue\n
-----END RSA PRIVATE KEY-----\n"

Step 2. Printing the value process.env.PRIVATE_KEY in your code will only show the first line: -----BEGIN RSA PRIVATE KEY-----\n. To fix this, edit the variable in .env to a single line. Like this:

PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\ndasdasdadasdasdasdasdasdasdasdadasdasdadasa\nhuehuauhhuauhahuauhauahuauhehuehuauheuhahue\n-----END RSA PRIVATE KEY-----\n"

Now process.env.PRIVATE_KEY will be outputted correctly.


You could use string.replace with a regular expression as below to escape the \n characters again:

"private_key": process.env.GATSBY_GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n'),