Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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-----"

In my gatsby-config file I have:

module.exports = {
    resolve: 'gatsby-source-google-sheets',
    options: {
        credentials: {
            "type": "service_account",
            "private_key": process.env.GATSBY_GOOGLE_PRIVATE_KEY,
            "client_id": process.env.GATSBY_GOOGLE_CLIENT_ID
        }
    }
}

The client_id works fine because it's just a one line string but the private_key doesn't work, presumably because it's multi line.

Is there a way I can get around this?

Thanks

like image 283
mckeever02 Avatar asked Apr 01 '19 16:04

mckeever02


People also ask

Are .env files private?

This article shows you how to use an env file in your code. This file stores all of our confidential information. It can be loaded once so you have access to all of your private information like passwords anywhere in your app.

Should you commit your .env file?

env files to version control (carefully) Many software projects require sensitive data which shouldn't be committed to version control. You don't want Bad Guys to read your usernames, passwords, API keys, etc.

Are .env files encrypted?

env contains sensitive information (passwords, tokens etc.) in clear-text so you don't want to place it in your versioned code. Using dotenvenc you generate from . env an encrypted version .


2 Answers

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'),
like image 81
John Sibly Avatar answered Oct 28 '22 19:10

John Sibly


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.
like image 34
Adarsh Madrecha Avatar answered Oct 28 '22 19:10

Adarsh Madrecha