Base64 are removing dots from string - java

I am trying to transform a string to byte and then get again as string, but the result was different. Have a look:
To decode:
byte[] tokenInBytes = Base64.decode(token, mFlags);
mTokenPreference.put(Base64.encodeToString(tokenInBytes, mFlags));
To get like a string again:
String value = Base64.encodeToString(tokenInBytes, mFlags);
The original string (before decode): eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVhMDA2ZTI4OGQ4ZDc1Z
And after was (after encode): eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJpZCI6IjVhMDA2ZTI4OGQ4ZDc1Z
Dots was removed. Anyone knows what I did wrong?
The value of mFlags was:
int mFlags = Base64.NO_WRAP | Base64.URL_SAFE | Base64.NO_PADDING;

You can replace your string value (dot) with any letter then after encode and decode replace same letter with dot.

I got this code from this link
// Sending side
byte[] data = value.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String value = new String(data, "UTF-8");

Related

Java: Converting byte string to byte array

I want to convert my byte[] to a String, and then convert that String to a byte[].
So,
byte[] b = myFunction();
String bstring = b.toString();
/* Here the methode to convert the bstring to byte[], and call it ser */
String deser = new String(ser);
bstring gives me [B#74e752bb.
And then convert the String to byte[]. I'm not using it in this order, but this is an example.
How do I need to do this in Java?
When converting byte[] to String, you should use this,
new String(b, "UTF-8");
instead of,
b.toString();
When you are converting byte array to String, you should always specify a character encoding and use the same encoding while converting back to byte array from String. Best is to use UTF-8 encoding as that is quite powerful and compact encoding and can represent over a million characters. If you don't specify a character encoding, then platform's default encoding may be used which may not be able to represent all characters properly when converted from byte array to String.
Your method when dealt appropriately, should be written something like this,
public static void main(String args[]) throws Exception {
byte[] b = myFunction();
// String bstring = b.toString(); // don't do this
String bstring = new String(b, "UTF-8");
byte[] ser = bstring.getBytes("UTF-8");
/* Here the methode to convert the bstring to byte[], and call it ser */
String deser = new String(ser, "UTF-8");
}
I am no expert, but you should try the methods provided by the "Byte" class and if necessary, some loops. Try byte b = Byte.parseByte(String s) to convert a string to a byte and String s = Byte.toString(byte b) to convert a byte to a string. Hope this helps :).
You can do it like this,
String string = "Your String";
byte[] bytesFromString = string.getBytes(); // get bytes from a String
String StringFromByteArray = new String(bytesFromString); // get the String from a byte array

How can I make a String Base64 Url Safe Java/Android?

I've been trying for a while but I can't seem to get my string to be Url Safe no matter what I do:
Input: XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT+d7yvxw=
Desired Output: XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT-d7yvxw
Essentially I want to apply some flags on my input string from https://developer.android.com/reference/android/util/Base64.html, namely Base64.URL_SAFE,Base64.NO_PADDING and Base64.NO_WRAP. However when I do:
String str = "XzbeW3jg9NYp6J0w2mTP4NLrTK06p1EDTnNG+KYhvyw=";
byte[] encoded = Base64.encode(
str.getBytes(), Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
byte[] strBytes = Base64.decode(encoded, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
String decoded = new String(strBytes);
//outputs original str "XzbeW3jg9NYp6J0w2mTP4NLrTK06p1EDTnNG+KYhvyw="
System.out.println(decoded);
I am not sure why the url safe encoding isn't working here, is there something I"m doing wrong? Is there a way I can get my desired output (besides manually doing String.replace() and other string modifications?
Thanks for the comments everyone! It was correct that I already had a base64 encoded string and I needed to decode first then re-encode.
byte[] strBytes = Base64.decode(str, Base64.DEFAULT);
byte[] encoded = Base64.encode(
strBytes, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
return new String(encoded);
is the solution that ended up working for me.

convert Hindi text to UTF-16 format

I want to convert my Hindi input to UTF-16 format. That's why I convert my string to byte array using character set "UTF-16".
But it will replace my string with ?????.
Here is the code
String original = "गुणवत्ता";
byte[] bytearr = original.getBytes("UTF-16");
String test= new String(bytearr,"UTF-16");
Try to encode the converted string as follows:
String original = "गुणवत्ता";
byte[] bytearr = original.getBytes("UTF-16");
String test= new String(bytearr,"UTF-16");
String encodedString = MimeUtility.encodeText(test, "utf-16", "B");

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.

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