Decoding the base64 part in a string in Java - java

I have encoded into base64 using the Java class built in. But when I try to decode I am having some issues. This code should explain what is happening:
String secondhalf=text.substring(text.length() / 3,text.length() / 3* 2);
byte[] secondhalfByte = secondhalf.getBytes();
secondhalf = Base64.getDecoder().decode(secondhalfByte);
I am getting the error:
cannot convert byte[] to String
What do I do?

To get an encoded string or a decoded byte[] use the following:
String secondhalf=text.substring(text.length() / 3,text.length() / 3* 2);
String encoded = Base64.getEncoder().encodeToString(secondhalf);
byte[] decoded = Base64.getDecoder().decode(encoded);
So you either want to encode your 'secondhalf' into a encoded string or then decode that into a byte[]

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")

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.

Java: Bits -> Bytes -> String Encoding

In Java, I have a String of bits e.g. "01100111000111...". Next, I want to do the following:
convert string to byte array which I have successfully done using:
byte[] bytes = new BigInteger(bits, 2).toByteArray();
Next, I want to convert bytes to String which I tried to do using:
String byteString = new String(bytes, "UTF-8");
but the results are not correct (garbage characters etc.).
I think "UTF-8" is not the proper encoding.
Kindly tell if there is any other way to get the string from such bytes or the proper encoding.
Edited after your comment:
String string = "01100111000111";
byte[] bytes = new BigInteger(string, 2).toByteArray();
String out = "";
for(byte b: bytes)
out+= String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
System.out.println(out);
output:
0001100111000111
Hope this can help.

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"));

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