Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 encoding in Java / Groovy

What is the proper way to convert a byte [] to a Base64 string in Java? Better yet would be Grails / Groovy because it tells me that the encodeAsBase64() function is deprecated. The sun.misc.BASE64Encoder package isn't recommended for use and outputs a different size string on some Windows platforms.

like image 932
Josh K Avatar asked Nov 15 '10 20:11

Josh K


People also ask

What characters are illegal in base64?

The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z', lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'. % is not allowed in base64 encoding.

Can base64 contain slashes?

No. The Base64 alphabet includes A-Z, a-z, 0-9 and + and / . You can replace them if you don't care about portability towards other applications.


1 Answers

The preferred way to do this in groovy is:

 def encoded = "Hello World".bytes.encodeBase64().toString()  assert encoded == "SGVsbG8gV29ybGQ="  def decoded = new String("SGVsbG8gV29ybGQ=".decodeBase64())  assert decoded == "Hello World" 
like image 50
ataylor Avatar answered Oct 03 '22 23:10

ataylor