Base64 string conversion to byte array not working properly - java

I'm trying to convert Base64 string into byte array using org.apache.commons.codec.binary.Base64
byte[] image = Base64.decodeBase64("Base64 String");
and then converting byte array to Base64 like
String Base64String = Base64.encodeBase64String(image);
but the base64String is different from the original base64 string. I dont get it where I went wrong

Use encodeBase64 not encodeBase64String.

Related

Convert InputStream to base64 and then to byte array

I need a byte array, but the requirement is like first I need to convert the input stream to base64 and then the base64 to byte array.
I have tried directly to the byte array, but the requirement is like need to convert the InputStream to base64 and then byte[].
InputStream input = ....
byte[] byteArray = IOUtils.toByteArray(input);
You can use Base64 from java.util package to encode your stream to base 64
Something like this:
String initialString = "original text";
InputStream input = new ByteArrayInputStream(initialString.getBytes());
byte[] byteEncoded = Base64.getEncoder().encode(IOUtils.toByteArray(input));
The method is Base64.getEncoder().encode and have 3 candidates:
public byte[] encode(byte[] src
public int encode(byte[] src,byte[] dst)
public ByteBuffer encode(ByteBuffer buffer)
Hoping that help

I converted BufferedImage to Base64 but How I convert it to Image again? [duplicate]

Okay, I know how to do it in C#.
It's as simple as:
Convert.ToBase64String(byte[])
and Convert.FromBase64String(string) to get byte[] back.
How can I do this in Java?
Java 8+
Encode or decode byte arrays:
byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded) // Outputs "Hello"
For more info, see Base64.
Java < 8
Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.
For direct byte arrays:
Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = codec.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(codec.decodeBase64(encoded));
println(decoded) // Outputs "Hello"
Spring
If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils class more ergonomic:
For direct byte arrays:
byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded)) // Outputs "Hello"
Android (with Java < 8)
If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64.
For direct byte arrays:
byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte [] decoded = Base64.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.decode(encoded));
println(decoded) // Outputs "Hello"
Use:
byte[] data = Base64.encode(base64str);
Encoding converts to Base64
You would need to reference commons codec from your project in order for that code to work.
For java8:
import java.util.Base64
Additionally, for our Android friends (API Level 8):
import android.util.Base64
...
Base64.encodeToString(bytes, Base64.DEFAULT);
In case you happen to be using Spring framework along with java, there is an easy way around.
Import the following.
import org.springframework.util.Base64Utils;
Convert like this.
byte[] bytearr ={0,1,2,3,4};
String encodedText = Base64Utils.encodeToString(bytearr);
To decode you can use the decodeToString method of the Base64Utils class.

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 pass byte array of an Image over a soap web-service(XML) and decode this byte array on android device to convert it back to an Image

I want to send images over a web service to an android device. This web service is written in VB.net and it is being called by android device to fetch the data. I can fetch the data normally, but the issue is with Images. I have converted image into byte array, converted it into string and passed it over web service(XML) to android device. I cannot decode this String byte array back to an image on android side. How to achieve this? Any simple solution? Am I using wrong approach?
For Converting Image To String :
String imageAsString=Base64.encodeToString(byteArray, Base64.DEFAULT);
For Converting String To Image:
byte[] imageAsBytes = Base64.decode(imageAsString.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView)findViewById(R.id.ImageView);
Bitmap imgBitmap=BitmapFactory.decodeByteArray(imageAsBytes,0,imageAsBytes.length);
image.setImageBitmap(imgBitmap);
Converting a byte array to a String is a bit tricky. Since the image data may contain null bytes, the String cannot. You probably need to encode the byte array so that the String is valid. Try to use base64-encoding.
Consider the following code example:
System.Convert.ToBase64String(byteArray)
You need to decode the base64-encoded String in android as well. Here is an example for that as well:
import org.apache.commons.codec.binary.Base64;
String base64String = "... your base64 String ...";
byte[] decodedBytes = Base64.decodeBase64(base64String.getBytes());
decodedBytes will contain your original data.
We got the solution
On webservice side we used:
System.Convert.ToBase64String(byte_arr)
On Android Side we used:
byte[] decodedBytes = Base64.decode(imageByteArray[i].getBytes(),Base64.DEFAULT);
Bitmap bMap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
Thank you for help. Cheers!!!
You can use org.castor.util.Base64Encoder to encode byte array to String
byte [] doc = {37, 80, 68, 70, 45, 49, 46};
String image = new String(Base64Encoder.encode(doc));
In your web service class, use this
byte[] imageData = Base64Decoder.decode(image);

Convert byte[] to String Java Android Encryption

I am using the JNCryptor library to encrypt a string before sending it to my server as an encrypted string. Here is my code:
String teststring = "Hello World";
JNCryptor cryptor = new AES256JNCryptor();
byte[] plaintext = teststring.getBytes();
String password = "test";
try {
byte[] ciphertext = cryptor.encryptData(plaintext, password.toCharArray());
String a = new String(ciphertext);
return a;
} catch (CryptorException e) {
// Something went wrong
e.printStackTrace();
return "0";
}
However, when I send my string "a" to the server, it has a bunch of unrecognizable characters. I read an explanation
regarding this:
String is not a suitable container for binary data and ciphertext is
binary data. For any given character encoding not all bytes and byte
sequences represents characters and when an un-representable byte or
sequence is found it is converted to some error character. Obviously
this error character cannot be converted back to a unique byte or byte
sequence (it is a many->one mapping).
Is this advice correct? In that case, how do I convert the byte[] to a string correctly? So that I can readably store it on my server?
There is no standard way for converting from a byte array to a string. You have to encode the byte array. A common way to do this is base64 encoding.
For an explanation of how base64 encoding works: http://en.wikipedia.org/wiki/Base64
Then once it gets to your server, base64 decode it back into your original byte array and store it, done!

Categories