This might seem super obvious to some of you, but this small problem had me stumped for a good 10 minutes this morning. I had an XML value that I was converting to Base64 for an HTTP post. Then, on the other side, I needed to take that Base64 encoded value and convert it back to a regular string for use with XML parsing. And then it hit, I had no idea how to, in ColdFusion, take a Base64 encoded value and convert it back to the original string.
Once I figured it out, it was laughably simple:
<!--- Create a string value. ---> <cfset strValue = "Hey there cutie patootie." /> <!--- Convert to base 64. ---> <cfset strBase64Value = ToBase64( strValue ) /> <!--- To convert the base 64 value back to string, simply convert the it a binary representation and then back into to a string. ---> <cfset strNewValue = ToString( ToBinary( strBase64Value ) ) /> <!--- Output test data. ---> <p> <cfoutput> Base 64: #strBase64Value#<br /> Value: #strNewValue# </cfoutput> </p>
Running the above code, we get the following output:
Base 64: SGV5IHRoZXJlIGN1dGllIHBhdG9vdGllLg==
Value: Hey there cutie patootie.
In ColdFusion, the ToBinary() function takes a Base64 encoded value and converts it to its binary representation. This, of course, is a Byte Array. In our example, where each character of a string is represented by a single byte, we have one character per byte array index. Then, calling ToString() on that Byte Array simply converts that character-based byte array back into its string representation.
Want to use code from this post? Check out the license.