How to normalize a private key stored on AWS secrets manager
I came up with a solution that leveraged storing a secret in secrets manager as plain text.
- Store the secret in secrets manager as plain text. They console will have JSON brackets but I removed those.
Use the cli to get the secret output as plain text. Now the \n and \s in the text will be converted to the line breaks and spaces they're supposed to be
aws secretsmanager get-secret-value --secret-id privatekey --query 'SecretString' --output text > private.pem
The pem file will now be properly formatted
-----BEGIN RSA PRIVATE KEY-----
MIIG3DCCBM
-----END RSA PRIVATE KEY-----
Another option would be to base64 encode the PEM for storage:
Encode the key:
$ cat private_key
-----BEGIN RSA PRIVATE KEY-----
asdkmnasefkljzsdkffjsldkgfjlzkmsdflkNOTAREALKEYasddkjnsfdlzxdfvlkmdggo=
-----END RSA PRIVATE KEY-----
$ base64 private_key > encoded_private_key
$ cat encoded_private_key
LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQphc2RrbW5hc2Vma2xqenNka2ZmanNsZGtnZmpsemttc2RmbGtOT1RBUkVBTEtFWWFzZGRram5zZmRsenhkZnZsa21kZ2dvPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=
Get the key back:
$ base64 -D encoded_private_key
-----BEGIN RSA PRIVATE KEY-----
asdkmnasefkljzsdkffjsldkgfjlzkmsdflkNOTAREALKEYasddkjnsfdlzxdfvlkmdggo=
-----END RSA PRIVATE KEY-----
Edit: Assuming the secret is base64 encoded, this would work:
Encode and push:
aws secretsmanager create-secret --name my-private-key --secret-string `base64 private.pem`
Pull and decode:
aws secretsmanager get-secret-value --secret-id my-private-key --query 'SecretString' --output text |base64 -D > private.pem
Doing the --query --output text thing might make it simpler to parse even if you don't want to base64 encode it as well.