How to convert a byte string to String? [duplicate] - java

I'm trying to decode a simple Base64 string, but am unable to do so. I'm currently using the org.apache.commons.codec.binary.Base64 package.
The test string I'm using is: abcdefg, encoded using PHP YWJjZGVmZw==.
This is the code I'm currently using:
Base64 decoder = new Base64();
byte[] decodedBytes = decoder.decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n") ;
The above code does not throw an error, but instead doesn't output the decoded string as expected.

Modify the package you're using:
import org.apache.commons.codec.binary.Base64;
And then use it like this:
byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

The following should work with the latest version of Apache common codec
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));
and for encoding
byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));

If you don't want to use apache, you can use Java8:
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n");

Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):
byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();

Related

Java - encode a string to Base64

I am converting a piece of javascript code to java and want to encode a string to Base64 in java.
Code in javascript:
let encodedData = btoa(String.fromCharCode.apply(null, new Uint8Array(array)))
This converts Uint8Array to string first and then encode it to Base64. But I am not able to find a way to do same in java.
Java code is
InputStream insputStream = new FileInputStream(file);
long length = file.length();
byte[] bytes = new byte[(int) length];
insputStream.read(bytes);
insputStream.close();
byte[] encodedBytes = Base64.getEncoder().encode(bytes);
Which is encoding bytes. Dues to which, encodedData(js) and encodedBytes(java) are not same.
What I want to do is something like:
String str = new String(bytes);
byte[] encodedBytes = Base64.getEncoder().encode(str); // ERROR: encode doesn't accept string
Is there any way to achieve this?
Base64.getEncoder().encode(str.getBytes(Charset)) may help you
(as Thomas noticed). But i can't guess your charset. The right syntax for Charset will be something like StandartCharsets.SOME_CHARSET or Charset.forName("some_charset")

How to convert byte array to base64 String

List<Map<String, Object>> lists = baseDao.getJdbcTemplate().queryForList(queryForImages, productId);
**System.out.println("size----" + lists.size());**
ArrayList<String> arrayList = new ArrayList<String>();
for (Map<String, Object> base64 : lists) {
byte[] imgData = (byte[]) base64.get("images");
String base64Encoded = new String(imgData, StandardCharsets.UTF_8);
// byte[] encodedImage = Base64.encodeBase64(imgData);
System.out.println("encoded---2" + base64Encoded);
}
i retrieve list of images from db and convert byte array to base64 string ,if i sysout only the last image in the list prints in sysout , even sysout list.size under the method is not printing .
In android, you can use Base64 (android.util.Base64) to encoded byte[] to String;
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
and
Decoding part as like following;
byte[] byteArray = org.apache.commons.codec.binary.Base64.decodeBase64(encodedString);
Usually this technique used in android app to send binary file/data to Server, using Web Service;
To start with, this is wrong:
String base64Encoded = new String(imgData, StandardCharsets.UTF_8);
The image bytes you have do not represent UTF-8 encoded text, so it makes no sense to create a String out of the bytes, pretending that this is UTF-8 encoded text.
If you are using Java 8, then use the Base64 class available in the standard library:
import java.util.Base64;
// ...
byte[] imgData = (byte[]) base64.get("images");
String base64Encoded = Base64.getEncoder().encodeToString(imgData);
If you are not using Java 8, you can use a third-party library, for example Apache Commons Codec, which includes classes for Base64 encoding and decoding.
If you are working with Android you can use the following code by importing the Android version of the Base64 class:
Base64.encodeToString(payload, Base64.DEFAULT);
From Android API 26, you can use java.util.Base64 as well.
Prior to java 1.8 use apache commons library
String base64 = new String(Base64.encodeBase64(imgData))

How to decode base64 in java

I am getting a base64encoded xml data in webservice response and I want to decode it in Java .
I tried org.apache.commons.codec.binary.Base64;
byte bytesEncoded[] = base64encodedStringfromWebservice.getBytes();
// Decrypt data on other side, by processing encoded data
byte[] valueDecoded= Base64.decodeBase64(bytesEncoded );
System.out.println("Decoded value is " + new String(valueDecoded));
but still some characters like (< , />) are not getting decoded properly .
Please suggest how to decode it correctly?
The getBytes method from String is platform specific. You need to specify an encoding, and later use that same encoding to decode the string. You can just use UTF8.
You also need to do the steps in reverse order: string -> base64 -> raw utf8 bytes -> base64 -> string
// ENCODE data
byte bytesEncoded[] = base64encodedStringfromWebservice.getBytes("UTF8");
// DECODE data on other side, by processing encoded data
String base64encodedStringfromWebservice = new String(bytesEncoded, "UTF8");
byte[] valueDecoded = Base64.decodeBase64(base64encodedStringfromWebservice);
System.out.println("Decoded value is " + new String(valueDecoded));
Try specifiying the charset you are using. for example, utf-8, and as you can see here: Decoding a Base64 string in Java
byte[] valueDecoded= Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded, "UTF-8"));

Java Mail MimeUtility encodeText UnsupportedEncodingException BASE64

As part of my J2EE application's email service, I encode into BASE64
body = MimeUtility.encodeText(orig_mail_body,"UTF-8","BASE64");
but in some circumstances it's throwing an exception:
java.io.UnsupportedEncodingException: Unknown transfer encoding: BASE64
at javax.mail.internet.MimeUtility.encodeWord(MimeUtility.java:565)
at javax.mail.internet.MimeUtility.encodeText(MimeUtility.java:373)
I've been trying to uncover why I get this particular message, but to no avail.
Can someone illuminate me?
It seems like the only valid values for the 'encoding' argument are "B" or "Q"; so my code should be:
body = MimeUtility.encodeText(orig_mail_body,"UTF-8","B");
if you're using java 8 now there is a class that can solve that.
byte[] bytes = orig_mail_body.getBytes();
Base64.Encoder encoder = Base64.getEncoder();
String encode = encoder.encodeToString(bytes);
System.out.print(encode);
with spring: org.springframework.security.crypto.codec
public static String base64Encode(String token) {
byte[] encodedBytes = Base64.encode(token.getBytes());
return new String(encodedBytes, Charset.forName("UTF-8"));
}
public static String base64Decode(String token) {
byte[] decodedBytes = Base64.decode(token.getBytes());
return new String(decodedBytes, Charset.forName("UTF-8"));
}
with apache commons
org.apache.commons.codec.binary.Base64;
byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
Salud

Decoding a Base64 string in Java

I'm trying to decode a simple Base64 string, but am unable to do so. I'm currently using the org.apache.commons.codec.binary.Base64 package.
The test string I'm using is: abcdefg, encoded using PHP YWJjZGVmZw==.
This is the code I'm currently using:
Base64 decoder = new Base64();
byte[] decodedBytes = decoder.decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n") ;
The above code does not throw an error, but instead doesn't output the decoded string as expected.
Modify the package you're using:
import org.apache.commons.codec.binary.Base64;
And then use it like this:
byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");
The following should work with the latest version of Apache common codec
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));
and for encoding
byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));
If you don't want to use apache, you can use Java8:
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n");
Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):
byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();

Categories