Skip to content Skip to sidebar Skip to footer

Using Private Key In A .env File

I have a multiline private key in a gatsby .env file: GATSBY_GOOGLE_CLIENT_ID='12345' GATSBY_GOOGLE_PRIVATE_KEY='-----BEGIN PRIVATE KEY-----\nflkdflkdf...\n-----END PRIVATE KEY----

Solution 1:

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'),

Solution 2:

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.

Solution 3:

I have similar issues where i have to read .pem file content. The following approach worked for me.

  • Convert the .pem content into base64 format
  • Put converted base64 content (this will be single line string) in .env file
  • Now decode env variable into original content

Solution 4:

Turns out the path to my .env was incorrect. For some reason the other keys were working but the private key was not.

The correct setup:

require("dotenv").config({
    path: `./.env.${process.env.NODE_ENV}`,
});
const private_key = process.env.GATSBY_GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n');

module.exports = {
    resolve: 'gatsby-source-google-sheets',
    options: {
        credentials: {
            "private_key": private_key,
        }
    }
}

Solution 5:

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.

Post a Comment for "Using Private Key In A .env File"