Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting byte array to base64 string java

Trying to convert a byte[] to base64 string using org.apache.commons.codec.binary.Base64..For this my java code looks like:

 base64String = Base64.encodeBase64URLSafeString(myByteArray);

But what i see is some invalid characters in the generated base64 string..ScreenShot

Why do I see these ____ lines in my generated base64 String? Is it a valid string? Note the length of the generated string is dividable by four.

like image 234
Suave Nti Avatar asked Jul 23 '12 12:07

Suave Nti


People also ask

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Is byte array and Base64 same?

You can use Base64's encode() method to convert Byte Array to Base64 String in Java. It encodes input without any line separation. In base64, length of encoded String should be multiple of 3. Sometimes, encode appends one or two padding characters to make it multiple of 3.

How do you convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java.

How do I get Base64 encoded strings?

In JavaScript there are two functions respectively for decoding and encoding Base64 strings: btoa() : creates a Base64-encoded ASCII string from a "string" of binary data ("btoa" should be read as "binary to ASCII"). atob() : decodes a Base64-encoded string ("atob" should be read as "ASCII to binary").


2 Answers

have you tried with the encodeBase64String method instead of using encodeBase64URLSafeString ?

encodeBase64URLSafeString:

Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The url-safe variation emits - and _ instead of + and / characters.

encodeBase64String:

Encodes binary data using the base64 algorithm but does not chunk the output. NOTE: We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to single-line non-chunking (commons-codec-1.5).

source : org.apache.commons.codec.binary.Base64 javadoc

like image 171
Jean-Philippe Caruana Avatar answered Sep 30 '22 09:09

Jean-Philippe Caruana


Use

String sCert = javax.xml.bind.DatatypeConverter.printBase64Binary(pk); 
like image 28
Taran Avatar answered Sep 30 '22 10:09

Taran