Java convert Base 64 value to Hex - java

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

Related

Difference between get byte array from string in C# and Java

I want to convert a string value to the same byte array in C# and Java with following codes:
C#:
string key="EA1302AFBCCF791CB0065BFAD948B092";
byte[] keyByte = Encoding.UTF8.GetBytes(plainKey);
Java:
String key="EA1302AFBCCF791CB0065BFAD948B092";
byte[] keyByte = (key).getBytes("UTF-8");
But the length of the generated array is 32 in C# and 343 in Java. I have to create a byte array in C# same as Java, so please don't suggest changes for my Java code.
I tried:
public static void main(String args[]) throws UnsupportedEncodingException {
String key="EA1302AFBCCF791CB0065BFAD948B092";
byte[] keyByte = key.getBytes("UTF-8");
System.out.println("Length: " + keyByte.length);
}
output is:
Length: 32

Convert String to Hex in Java

I want using CRC16, but first, i want to convert string to hex. because integer must be 16 bytes. i still confused to encrypt using CRC16. this is my code.
public static void main(String[] args) {
String input = "skn";
byte[] valuesDefault = input.getBytes();
System.out.println("input:" + input);
System.out.println(Arrays.toString(valuesDefault));
}
Try this below
DatatypeConverter.printHexBinary(input.getBytes())

Base64 Encoding: Illegal base64 character 3c

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

Base64 Java encode and decode a string [duplicate]

This question already has answers here:
Encoding as Base64 in Java
(19 answers)
Closed 7 years ago.
I want to encode a string into base64 and transfer it through a socket and decode it back.
But after decoding it gives different answer.
Following is my code and result is "77+9x6s="
import javax.xml.bind.DatatypeConverter;
public class f{
public static void main(String a[]){
String str = new String(DatatypeConverter.parseBase64Binary("user:123"));
String res = DatatypeConverter.printBase64Binary(str.getBytes());
System.out.println(res);
}
}
Any idea about how to implement this?
You can use following approach:
import org.apache.commons.codec.binary.Base64;
// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));
// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));
Hope this answers your doubt.
Java 8 now supports BASE64 Encoding and Decoding. You can use the following classes:
java.util.Base64, java.util.Base64.Encoder and java.util.Base64.Decoder.
Example usage:
// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);
// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);
// decode a String
byte [] barr = Base64.getDecoder().decode(encoded);
The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries
Java 11 and up
import java.util.Base64;
public class Base64Encoding {
public static void main(String[] args) {
Base64.Encoder enc = Base64.getEncoder();
Base64.Decoder dec = Base64.getDecoder();
String str = "77+9x6s=";
// encode data using BASE64
String encoded = enc.encodeToString(str.getBytes());
System.out.println("encoded value is \t" + encoded);
// Decode data
String decoded = new String(dec.decode(encoded));
System.out.println("decoded value is \t" + decoded);
System.out.println("original value is \t" + str);
}
}
Java 6 - 10
import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter;
public class EncodeString64 {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "77+9x6s=";
// encode data using BASE64
String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
System.out.println("encoded value is \t" + encoded);
// Decode data
String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
System.out.println("decoded value is \t" + decoded);
System.out.println("original value is \t" + str);
}
}
The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.
For Spring Users , Spring Security has a Base64 class in the org.springframework.security.crypto.codec package that can also be used for encoding and decoding of Base64.
Ex.
public static String base64Encode(String token) {
byte[] encodedBytes = Base64.encode(token.getBytes());
return new String(encodedBytes, Charset.forName("UTF-8"));
}
public static String base64Decode(String token) {
byte[] decodedBytes = Base64.decode(token.getBytes());
return new String(decodedBytes, Charset.forName("UTF-8"));
}
The following is a good solution -
import android.util.Base64;
String converted = Base64.encodeToString(toConvert.toString().getBytes(), Base64.DEFAULT);
String stringFromBase = new String(Base64.decode(converted, Base64.DEFAULT));
That's it. A single line encoding and decoding.
import javax.xml.bind.DatatypeConverter;
public class f{
public static void main(String a[]){
String str = new String(DatatypeConverter.printBase64Binary(new String("user:123").getBytes()));
String res = DatatypeConverter.parseBase64Binary(str);
System.out.println(res);
}
}

Need Java equvalent for 3DES decryption of PHP code

This is the PHP code I have.
function decrypt($s_input, $s_key, $s_iv) {
$s_decrypted = pack("H*" , $s_input); // Hex to binary
$s_decrypted = mcrypt_decrypt (MCRYPT_3DES, $s_key, $s_decrypted, MCRYPT_MODE_CBC, $s_iv); // 3des decryption
return $s_decrypted;
}
echo encrypt('c37551bb77f741d0bcdc16497b4f97b1','123456781234567812345678','12345678' );
what it basically does is to decrypt a 3des encrypted string (first it convert the hex string to binary using pack function and then does the actual decryption).
This perfectly works in PHP-4 and prints the "Hello World" message.
However, if I run the equivalent java code (jdk 1.6), it prints garbage output as - ¬ªmjV=7xl_ÓÄ^›*?.
Can someone help to troubleshoot this? Why Java is not properly decrypting the hex string.
private static String decrypt(String inputStr, String keyStr, String ivStr) throws Exception {
IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
SecretKeySpec key = new SecretKeySpec(keyStr.getBytes(), "DESede");
inputStr = hexToString(inputStr, 2);
Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decrypted = cipher.doFinal(inputStr.getBytes());
return new String(decrypted);
}
private static String hexToString(String input, int groupLength) {
StringBuilder sb = new StringBuilder(input.length() / groupLength);
for (int i = 0; i < input.length() - groupLength + 1; i += groupLength) {
String hex = input.substring(i, i + groupLength);
sb.append((char) Integer.parseInt(hex, 16));
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
String decryptSignature = decrypt("c37551bb77f741d0bcdc16497b4f97b1", "123456781234567812345678", "12345678");
System.out.println(decryptSignature);
}
There are a few things you should check. You might find Encryption using AES-128 in Java to be of some assistance. There could be issues with differences between how you are handling keys in the PHP and Java code. Calling getBytes() on a String in Java without an encoding is almost always a bad idea. Plus the padding used could be a problem. From what I've seen PHP pads with null characters by default, which does not correspond to NoPadding in Java. Finally, the hexToString method should return a byte[] instead of a String. Add the result of calling Integer.parseInt(hex, 16) into an array:
byte[] results = new byte[input.length() / groupLength];
...
//inside the loop
results[i / groupLength] = (byte) Integer.parseInt(hex, 16);
...
return results;

Categories

Resources