简体   繁体   中英

Laravel - Can't get .pem public key data from .env file

I have an webapp built with Laravel and i need to use a public key from a .pem file to verify some data. The key is kept in the .env file and retrieved via config/app.php with the env() helper. Since the .pem key needs to be on separate lines with specific length i use \\n characters to keep the key on one line. Problem is that when i use the \\n characters the variable is not cached and i cannot access it. When i remove the \\n characters i can retrieve the variable but the openssl_get_privatekey($key); returns false. What am i doing wrong? Is this a Laravel or some general PHP issue?

PHP's dotenv package does not seem to support multi-line environment variables.

You should ideally keep your .pem file as a file and reference it by path like eg:

PEM_FILE=/path/to/file.pem

and in the config:

return [
    //...
    "key" => file_get_contents(env('PEM_FILE'))

This makes sense since generally certificates should generally go in the dedicated certificates path on the server. If you cache the config then the actual contents of the .pem file are only read once on deployment.

However if you must put it in dotenv then you can do:

In .env

PEM_KEY="-----BEGIN RSA PRIVATE KEY-----\n…\n-----END DSA PRIVATE KEY-----"

In configs:

return [
    //...
    "key" => str_replace("\\n", "\n", env('PEM_KEY')), 

Since the key is generally base64 I don't think there's a chance \\n would naturally occur inside a .pem file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM