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..
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.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
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.
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.
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").
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With