I've been using
Apache's Commons Codec to encode and decode base64 data. The
Groovy code:
import org.apache.commons.codec.binary.Base64
def data = "data"
def bytes = data.bytes
Base64 coder = new Base64()
def encodedData = coder.encode(bytes)
def decodedData = coder.decode(encodedData)
println "Original Data: $data"
println "Encoded Data: " + new String(encodedData)
println "Decoded Data: " + new String(decodedData)
Producing:
Original Data: data
Encoded Data: ZGF0YQ==
Decoded Data: data
But
Groovy makes it easy thru its additions to the
JDK:
encodedData = bytes.encodeBase64().toString()
def decodedBytes = encodedData.decodeBase64()
decodedData = new String(decodedBytes)
println "Groovy Encoded Data: $encodedData"
println "Groovy Decoded Data: $decodedData"
Which produces:
Groovy Encoded Data: ZGF0YQ==
Groovy Decoded Data: data
Maven coordinates for
commons-codec:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.3</version>
</dependency>
Suggestions for alternative appreciated as always.
Thanks for the post.
ReplyDeleteYou do know that Groovy now has the EncodingGroovyMethods class, which replaces the deprecated encode/decode methods on byte[] and String, respectively? It would be interesting to read about the differences between the available solutions…
ReplyDeleteThis doesn't seem toe base64 encode correctly. I have no idea what it's encoding to, but it's not base64
ReplyDeleteyou can compare the result with the one from http://base64encode.net
DeleteThis tool encodes certain characters in a URL by replacing them with one or more character like % followed by hexadecimal digits.
ReplyDeleteencoder decoder online