I need to send base64Binary into SOAP service. I have this method in class, which create base64String:
public String encode(final String text) {
byte[] msgBytes = text.getBytes(StandardCharsets.UTF-8);
String base64String = DatatypeConverter.printBase64Binary(messageBytes);
return base64String;
}
How can I convert base64String into base64Binary with bytes into base64String?
DatatypeConverter.parseBase64Binary can be used to decode a Base64 encoded String:
byte[] msgBytes = DatatypeConverter.parseBase64Binary(base64String);
If you want to convert the byte[] to a String, you can proceed like:
String text = new String(msgBytes , "UTF-8");
Related
I want to decode a string to UTF-8 format in java. In the following code, I am able to get the expected decoded value from String decoded.
String s = "SFSFSFSFSF";
Base32 codec = new Base32();
String encoded = codec.encodeAsString(s.toUpperCase().getBytes());
Charset UTF_8 = Charset.forName("UTF-8");
String decoded =new String(codec.decode(encoded),UTF_8); // SFSFSFSFSF
String decoded2 = codec.decode(encoded); // [B#133314b
However, in my implementation specifically, I want to get the decoded val "SFSFSFSFSF" just by saying codec.decode(encoded) which is demonstrated in String decoded2 in the code. I want to know how I can achieve this by changing the way the String is encoded.
I have generated Base64 encoded value using below Scala code:
println(Base64.getEncoder.encodeToString("E5E9FA1BA31ECD1AE84F75CAAA474F3A".getBytes(StandardCharsets.UTF_8)))
YxRfXk827kPgkmMUX15PNg==
Now I am trying to convert "YxRfXk827kPgkmMUX15PNg==" to Hex. I tried with below Java code but no luck:
public static void main(String[] args) throws DecoderException {
String guid = "RTVFOUZBMUJBMzFFQ0QxQUU4NEY3NUNBQUE0NzRGM0E=";
byte[] hexString = Hex.decodeHex(guid);
System.out.println(hexString);
Exception in thread "main" org.apache.commons.codec.DecoderException: Illegal hexadecimal character R at index 0
When I explored I found below working Java code:
String guid = "YxRfXk827kPgkmMUX15PNg==";
byte[] decoded = Base64.decodeBase64(guid);
String hexString = Hex.encodeHexString(decoded);
System.out.println(hexString);
4535453946413142413331454344314145383446373543414141343734463341
But here Base64 values is getting decoded and then converted to Hex. I am trying to figure out if there is a way we can directly convert Base64 to Hex? Please excuse as it looks like a duplicate question and thanks in advance.
Since it is a String, it already has a way to get the ByteArray.
Don't decode the Base64, simply request the bytes from the String:
public static void main(String[] args) {
String guid = "YxRfXk827kPgkmMUX15PNg==";
String hexString = Hex.encodeHexString(guid.getBytes());
System.out.println(hexString);
}
This basically means you only have to convert your string to a Byte[].
You can see that the business logic code is very simple and that the original text and the hex encoded are the same by trying to decode them in a test:
// actual business logic
public String hexEncoder(String content) {
return Hex.encodeHexString(content.getBytes());
}
// input and assertion
#Test
public void hexEncoder() throws DecoderException {
String guid = "YxRfXk827kPgkmMUX15PNg==";
String hexString = hexEncoder(guid);
String hexDecoded = new String(Hex.decodeHex(hexString));
// no need to decode Base64 but might be useful for `printLn` or debugging
String s = new String(Base64.decodeBase64(guid));
String s1 = new String(Base64.decodeBase64(hexDecoded));
assertEquals(s, s1);
}
Decoding with base64 an unencoded string on Android does not gives any error but returns a string with some special characters e.g encoded like.
It should throw some IllegalArgumentException. Is there some native way in android to check that other than regex ?
private String decodeThisString = "I am a java String";
bytes[] deocdedBytes = Base64.decode(decodeThisString.getBytes(), Base64.DEFAULT);
I think you do not need to remove the character when you will decode it, automatically they will be discarded at the time of decode. I have tested with encoding and decoding with the provided code and get the exact string after decode.
String decodeThisString = "I am a java String";
//encode
byte[] data = Base64.encode(decodeThisString.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);
//decode
byte[] datas = Base64.decode(text, Base64.DEFAULT);
String texts = new String(datas, StandardCharsets.UTF_8);
I am trying to decode data in an xml format into bytes base64 and I am having an issues. My method is in java which takes a String data and converts it into bytes like as bellow.
String data = "......"; //string of data in xml format
byte[] dataBytes = Base64.getDecoder().decode(data);
Which failed and gave the exception like bellow.
java.lang.IllegalArgumentException: Illegal base64 character 3c
at java.util.Base64$Decoder.decode0(Base64.java:714)
at java.util.Base64$Decoder.decode(Base64.java:526)
at java.util.Base64$Decoder.decode(Base64.java:549)
at XmlReader.main(XmlReader.java:61)
Is the xml format not compatible with base64?
Just use this method
getMimeDecoder()
String data = "......";
byte[] dataBytes = Base64.getMimeDecoder().decode(data);
I got this same error and problem was that the string was starting with data:image/png;base64, ...
The solution was:
byte[] imgBytes = Base64.getMimeDecoder().decode(imgBase64.split(",")[1]);
You should first get the bytes out of the string (in some character encoding).
For these bytes you use the encoder to create the Base64 representation for that bytes.
This Base64 string can then be decoded back to bytes and with the same encoding you convert these bytes to a string.
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Base64Example {
public static void main(String[] args) {
final String xml = "<root-node><sub-node/></root-node>";
final byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8);
final String xmlBase64 = Base64.getEncoder().encodeToString(xmlBytes);
System.out.println(xml);
System.out.println(xmlBase64);
final byte[] xmlBytesDecoded = Base64.getDecoder().decode(xmlBase64);
final String xmlDecoded = new String(xmlBytesDecoded, StandardCharsets.UTF_8);
System.out.println(xmlDecoded);
}
}
Output is:
<root-node><sub-node/></root-node>
PHJvb3Qtbm9kZT48c3ViLW5vZGUvPjwvcm9vdC1ub2RlPg==
<root-node><sub-node/></root-node>
Thanks to #luk2302 I was able to resolve the issue. Before decoding the string, I need to first encode it to Base64
byte[] dataBytes = Base64.getEncoder().encode(data.getBytes());
dataBytes = Base64.getDecoder().decode(dataBytes);
I have some code that is working correctly in Java but when I try to use it in Android it is having problems.
I am attempting to encrypt an SMS text message with the Blowfish algorithm.
The problem with this code (on android) is that it will not accept the byte[] and will not decrypt the message.
SENDING THE SMS
sMessage = "hello this is a message"
byte[] byteArray = EncryptBlowfish(sMessage);
//Convert the byte[] into a String which can be sent over SMS
StringBuffer strb = new StringBuffer();
for( int x = 0; x<byteArray.length; x++){
strb.append(byteArray[x]).append(",");
}//for loop
sMessage = strb.toString();
(sMessage is then sent via SMS)
RECIVING THE SMS
//Convert the String back to a byte[] which can be decrypted
String[] strArray = sMessage.split(",");
byte[] byteArray = new byte[strArray.length];
int hold;
for (int x = 0; x < strArray.length; x++) {
hold = Integer.parseInt(strArray[x]);
byteArray[x] = (byte) hold;
}//for loop
sMessage = DecryptBlowfish(byteArray);
Encryption Method
public static byte[] EncryptBlowfish(String msg){
byte[] encrypted =null;
try {
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
encrypted = cipher.doFinal(msg.getBytes());
} catch (){ //NoSuchAlgorithmException, NoSuchPaddingException..etc
}
return encrypted;
}
Decryption Method
public static String DecryptBlowfish(byte[] msg){
byte[] decrypted =null;
try {
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, secretkey);
decrypted = cipher.doFinal(msg);
} catch (){ //NoSuchAlgorithmException, NoSuchPaddingException..etc
}
return decrypted;
}
The message is being encrypted, this creates a byte[], I have then converted the byte[] to a string, the string's output will look something like this...
46,77,52,11,-108,91,-106,88,-81,-43,14,111,-118,-128,-92,-50,69,-44,100,-94,71,92,-49,116,
this output is then sent over SMS. The string is then convert back into a byte[]
but this byte array is not decrypting.
Questions:
Why would this code work in a Java app, but not Android?
Is there a way of making this work in Android?
Is there a better method of converting the byte[] to a String and back.
(Please comment if anymore information is require, Thanks)
I think the answer involves what the default character encoding is on Android vs standard Java. What happens if you specify the character encoding using msg.getBytes(Charset c), and for decoding new String(byte [], Charset c).
Example:
// String => byte []
byte[] bytes = message.getBytes(Charset.forName("ISO-8859-1"));
// byte [] => String
String foo = new String(bytes, Charset.forName("ISO-8859-1"));
You can find what character sets are available from:
for (String c : Charset.availableCharsets().keySet()) {
System.out.println(c);
}
I think there is a problem when you make byte -> string -> byte conversion. Try to send an unencrypted string and retrieve it and check if it is correct.
You should probably specify the encoding at each step.
To convert from a byte array to a string use this
Base64.encodeToString(byteArray, Base64.NO_WRAP);
To convert from a string to a byte array use this
Base64.decode(string, Base64.DEFAULT);
The Base64 class is in the android.util package.