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"));
Related
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.
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))
I've got an encrypted string in PHP and need to send this in an HTTP request. So I decide to use Base64 encoding and URL encoding. The received is a Java module; but when I use the Base64 decoder, it shows me a completely different string. How can I get the original encrypted string back. I need actually to pick each character from that original string and use its corresponding ASCII code for decryption.
// PHP code
$encrypted = "©’Ÿ£ šd¤¨m";
$base64 = base64_encode($string);
$parameter = urlencode($base64);
// this returns eventually: qZKfo6CaZKSobQ%3D%3D
// Java code
// FYI: the variable "name" is a string that the Java software extracts from the posted data.
String base64 = java.net.URLDecoder.decode(name, "UTF-8");
byte[] bytes = java.util.Base64.getDecoder().decode(base64);
String encrypted = new String(bytes);
// This returns: ������d��m
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!
how to encrypt cookies as it accepts only US-ASCII characters? when i use below code, it generates characters out of US_ASCII. how to limit encrypted characters not to go out of US_ASCII?
key = KeyGenerator.getInstance(algorithm).generateKey();
cipher = Cipher.getInstance("DESede");
messageSource.getMessage("encryption.algorithm",null,localeUtil.getLocale());
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] outputBytes = cipher.doFinal(input.getBytes());
Firstly: don't use String.getBytes without specifying an encoding, preferably something which can handle all of Unicode, such as UTF-8.
Secondly: the code you've given doesn't generate characters at all - it generates bytes. You mustn't treat those bytes as if they're encoded text - they're not. Instead, you should convert them to base64, e.g. with Apache Commons Codec or this public domain code.
Then when you need to decrypt, you simply reverse all the steps - convert back from base64 to binary, decrypt, and then create a string with new String(decryptedBytes, "UTF-8") (or whatever encoding you decided to use).
public static final String CHARSET = "ISO-8859-1";
String text = "Ángel";
String encodedText = new String(Base64.encodeBase64(text.getBytes(CHARSET)));
String decodedText = new String(Base64.decodeBase64(encodedText.getBytes(CHARSET)))
In addition to Jon's answer, you can view the available encodings here:
http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html