Thursday, June 18, 2009

Groovy: Base64 encode/decode with and without Commons Codec

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.

5 comments:

  1. You 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…

    ReplyDelete
  2. This doesn't seem toe base64 encode correctly. I have no idea what it's encoding to, but it's not base64

    ReplyDelete
    Replies
    1. you can compare the result with the one from http://base64encode.net

      Delete
  3. This tool encodes certain characters in a URL by replacing them with one or more character like % followed by hexadecimal digits.
    encoder decoder online

    ReplyDelete