It’s common practice to encode non-ASCII data (such as RSA keys or binary data) as a single-line Base64-encoded string before setting it as an environment variable.
Before learning about this TIL, I used to do this:
$ cat key.pub | base64
c3NoLXJzYSBBQUFBQjNOemFDMXljMkVBQUFBREFRQUJBQUFDQVFEYkJrb3FIRUFyTUliYThjbktW
ZEJaOEpnRWVJUDF2WnJkVE1uUU5LS2EvU0lXd2ZTNXNienNId1dabk5YRTNWZWVnRllrRjlva29D
SThMUEVGVmRSVEtMcURYZzByZUQvdnh4UjlLYnVmUUVVR2RKQW0yMjdmZHRxc2RVZUt3VS9IWjdR
SkxidEhES1JBV05kdVJwMjBnTzJOSVBSS3JaaHFOeXNCZVBkanpZN09oUmVPbS9YRlVMUC94ZktC
RUZoWVc4YlB1NzJnbGhvWTM0ZFNTVlNGN1JvOFRZS1FSaHVab3psL1licWxUTlZhTU1CbmU0eFVz
ZVF5WmlaZVYxUDlOaHBUU1pMRkM0TElHRElDOGJKbjVqa1k4MHEvbHpxL1BwTU5URVhZUDg1NVNp
RjRSbkxkU0ZrWUxOaUFpcHdmWUdsa0J3QTB0M0RFQlYzNS9UL09TM0tiVzJDbDh1aFREcnJ2LzFR
YmRHWDAvM2kvMTZvZUxWZldtM1QrNFZpNURnSFFEL0wrdkFGTVlVbzBZd1kxeHJKb2d5Wjl4K1R5
N0hnQ1hkL2ZxTG9nVlcrb2dDRnVMWmRZd2ZoMWU5WEd0VGRQN2FKRkJoSGp4QlBLZFZEQ3RpL2dX
UzZ3YkQrd2JKTmlUTUJ1MWJmQVM5Um1RSkJoSVUyWHk3ek9XR2ZUOVZyeXUwM2pYdTJoZ0ZvMXk0
RVpsT2NoZ1ZrRmU1UDZVWUwxZ1hwdHBxVlVPR3FiZU5FVG9jV2Y0T1hIK05XM2RTZlZGNnZzTlJE
RWlkSWVFRUliVVlwSlhDM1IwNkZFZzFSOTRPQzNuSW05Zk52NytRYVN3WUgycTVYTkM5c0p0NHZl
QVJCWXlEeW1LZ0dnSlp3V2VhL2dVdW8yK0FtZXQwVUZUamdrT3c9PSByZW1pQHpvZS5sb2NhbAo=
And then, manually remove any newline characters to make it a single-line string 😩
However, there’s this neat option with base64
that allows us to avoid outputting any newline characters at all!
On macOS (/usr/bin/base64
):
$ cat key.pub | base64 --break 0
c3NoLXJzYSBBQUFBQjNOemFDMXljMkVBQUFBREFRQUJBQUFDQVFEYkJrb3FIRUFyTUliYThjbktWZEJaOEpnRWVJUDF2WnJkVE1uUU5LS2EvU0lXd2ZTNXNi…
On Linux (or if you have GNU coreutils
installed on macOS using Homebrew):
$ cat key.pub | base64 --wrap 0
c3NoLXJzYSBBQUFBQjNOemFDMXljMkVBQUFBREFRQUJBQUFDQVFEYkJrb3FIRUFyTUliYThjbktWZEJaOEpnRWVJUDF2WnJkVE1uUU5LS2EvU0lXd2ZTNXNi…
We now have an environment variable-friendly string!
🎉