When writing scripts, it’s sometimes useful to be able to be able to include and deploy binary files as part of the script run. An example of this would be if you want to use MySQL 5.6 and later’s option for creating a MySQL connection file. This is a file that allows you to store MySQL authentication inside an encrypted file named .mylogin.cnf.
Rather than trying to script the creation of a MySQL connection file, where the creation process would involve placing the MySQL authentication credentials in a readable format inside the script, it is easier and more secure to build the connection file manually on one machine and then encode the encrypted MySQL connection file into ASCII text using base64 encoding. Once encoded, the ASCII text can be decoded as part of a script designed to deploy the still-encrypted MySQL connection file to a desired location.
For more details on how to use base64 encoding, please see below the jump.
To encode files, you can use the openssl utility’s base64 function to encode them as ASCII characters. For example, a file named hello_world.txt with the following contents needs to be copied to the same location on multiple Macs:
-------- Hello, World! ---------
To encode the file, run the following command:
openssl base64 < /path/to/hello_world.txt
That will give you a ASCII string like that shown below:
LS0tLS0tLS0KCkhlbGxvLCBXb3JsZCEKCi0tLS0tLS0tLQo=
You can then embed the string in a script and have it read back into a new file. For example, the script shown below will decode and store a copy of the hello_world.txt file inside the /Users/Shared directory:
#!/bin/bash # Decode hello_world.txt stored in base64 format # and store it as /Users/Shared/hello_world.txt. openssl base64 -d <<HELLOWORLD > /Users/Shared/hello_world.txt LS0tLS0tLS0KCkhlbGxvLCBXb3JsZCEKCi0tLS0tLS0tLQo= HELLOWORLD
Running the script on the desired machines will allow the hello_world.txt file to be deployed into the desired location inside the /Users/Shared directory.
As files get larger, the block of ASCII text will also grow. Encoding the script shown above will produce a block of ASCII text that looks similar to this:
IyEvYmluL2Jhc2gKCiMgRGVjb2RlIGhlbGxvX3dvcmxkLnR4dCBzdG9yZWQgaW4g YmFzZTY0IGZvcm1hdCAKIyBhbmQgc3RvcmUgaXQgYXMgL1VzZXJzL1NoYXJlZC9o ZWxsb193b3JsZC50eHQuCgpvcGVuc3NsIGJhc2U2NCAtZCA8PEhFTExPV09STEQg PiAvcGF0aC90by9oZWxsb193b3JsZC50eHQKTFMwdExTMHRMUzBLQ2tobGJHeHZM Q0JYYjNKc1pDRUtDaTB0TFMwdExTMHRMUW89CkhFTExPV09STEQK
This encoding technique can also be used to deploy entire executable binaries, where the program in question is encoded using the technique described above, then deployed to a desired location.