How to store PEM/P8 key in Secrets?

I’m trying to save the contents of a .p8 file in secrets. Typically, the contents would look something like this:

-----BEGIN PRIVATE KEY-----
MIGTAgEANBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgnu1O+vrbXT6IY6xY
jyHBzvL0LFyzjE6qENqWmgjf4DSGCgYIKoZIzj0DAQehRANCAARr96LHJSLoApun
yxf0umUPYcBvdjy2yeTrZMjmTQ0Biddl+xsTjJMLvfvnIwgNYQasHpshvarDlyC8
mBqkjg2N
-----END PRIVATE KEY-----

When I paste it to secrets, it’s saved in one line and once retrieved, seems to be malformed because I cannot initialize the push notification client that requires it. I say “seems” because the client initializer that requires the key errors out.

However, if I hard-code the key in the app as shown above (respecting the multi lines), then it works fine and the client initializes properly.

Is there a way to make it work using secrets?

1 Like

If you can use a base64 encoded secret, then yes.

See this discussion: How are you managing cert files with Fly? - #16 by michael

1 Like

I ended up encoding the newlines (replacing them with \n (the actual two characters, not the escape sequence) and then translate them back to real newlines in the app. Something like this:

func encodePEMKey(_ key: String) -> String {
    return key.replacingOccurrences(of: "\n", with: "\\n")
}

func decodePEMKey(_ encodedKey: String) -> String {
    return encodedKey.replacingOccurrences(of: "\\n", with: "\n")
}

Works fine now. Thanks!

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.