How to decode hex code in an array in java - java

Need to decode hex code in array when accessed by index.User should enter array index and get decoded hex in array as output.
import java.util.Scanner;
class Find {
static String[] data={ " \\x6C\\x65\\x6E\\x67\\x74\\x68",
"\\x73\\x68\\x69\\x66\\x74"
//....etc upto 850 index
};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int s = in.nextInt();
String decodeinput=data[s];
// need to add some code here
//to decode hex and store to a string decodeoutput to print it
String decodeoutput=......
System.out.println();
}
}
How about using...
String hexString ="some hex string";
byte[] bytes = Hex.decodeHex(hexString .toCharArray());
System.out.println(new String(bytes, "UTF-8"));

Append the following code after getting the value of s from user. Imp: Please use camelCase convention for naming variables as pointed out above. I have just gone ahead and used the same names as you have for your convinience for now.
if (s>= 0 && s < data.length) {
String decodeinput = data[s].trim();
StringBuilder decodeoutput = new StringBuilder();
for (int i = 2; i < decodeinput.length() - 1; i += 4) {
// Extract the hex values in pairs
String temp = decodeinput.substring(i, (i + 2));
// convert hex to decimal equivalent and then convert it to character
decodeoutput.append((char) Integer.parseInt(temp, 16));
}
System.out.println("ASCII equivalent : " + decodeoutput.toString());
}
OR, just complete what you were doing:
/* import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex; //present in commons-codec-1.7.jar
*/
if (s>= 0 && s < data.length) {
String hexString =data[s].trim();
hexString = hexString.replace("\\x", "");
byte[] bytes;
try {
bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println("ASCII equivalent : " + new String(bytes, "UTF-8"));
} catch (DecoderException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

Related

How to convert hexstring to ANSI (window 1252) and convert ANSI (window 1252) back to hex string in Java?

How to convert hex string to ansi (window 1252) and ansi (window 1252)to hex string in Java.
python (Works perfectly)
q = "hex string value"
x = bytes.fromhex(q).decode('ANSI')
a = x.encode("ANSI")
a = a.hex()
if q==a:
print("Correct")
Java (This code has a problem)
String hexOri = "hex string value";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hexOri.length(); i+=2) {
String str = hexOri.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println("ANSI = " + output);
char [] chars = output.toString().toCharArray();
StringBuffer hexOutput = new StringBuffer();
for(int i = 0; i < chars.length; i++){
hexOutput.append(Integer.toHexString((int)chars[i]));
}
System.out.println("HexOutput = " + hexOutput.toString());
System.out.println(hexOri.equals(hexOutput.toString()));
Output from Python
Correct
Expected Output from Python
Correct
Output from Java
False
Expected Output from Java
Correct
In java the strings are encoded in UTF-16, so you can't read simply read/write the bytes of a string to get the encoding representation you desire.
You should use String#getBytes(String str, String charset) to get the string converted in the encoding you need and serialized to a byte array.
The same thing must be done to decode a byte array, using new String(buffer,encoding).
In both cases if you use the method without the charset it will use the default encoding for the JVM instance (which should be the system charset).
public static void main(String[] args) {
String str = "\tSome text [à]";
try {
System.out.println(str); // Some text [à]
String windowsLatin1 = "Cp1252";
String hexString = toHex(windowsLatin1, str);
System.out.println(hexString); // 09536f6d652074657874205be05d
String winString = toString(windowsLatin1, hexString);
System.out.println(winString); // Some text [à]
} catch (UnsupportedEncodingException e) {
// Should not happen.
}
}
public static String toString(String encoding, String hexString) throws UnsupportedEncodingException {
int length = hexString.length();
byte [] buffer = new byte[length/2];
for (int i = 0; i < length ; i+=2) {
String hexVal = hexString.substring(i,i+2);
byte code = (byte) Integer.parseInt(hexVal,16);
buffer[i/2]=code;
}
String winString = new String(buffer,encoding);
return winString;
}
public static String toHex(String encoding, String str) throws UnsupportedEncodingException {
byte[] bytes = str.getBytes(encoding);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
String hexChar = Integer.toHexString(b & 0xff);
if(hexChar.length()<2) {
builder.append('0');
}
builder.append(hexChar);
}
String hexString = builder.toString(); // 09536f6d652074657874205be05d
return hexString;
}

Attempting to decrypt encrypted hexadecimal code, find key, and convert to english

Goal: Decode encrypted hex, which requires finding an unknown, single character key
I was purely trying to do the problem by XOR'ing each character in xOR with each of the ascii characters. I was expecting to get a String of hexes as one of my outputs. However, my catch statement says that every string it returns is not hex.
I then planned to take these converted hexvalues and just cast them as chars.
If you could offer me some guidance on how to fix this atrocity, it would be greatly appreicated.
Thanks a bunch!
//intention of this program is to decrypt this string of encoded hex, find the key, and decrpt the message
//however, its not really working. It doesnt print values prior to 112 even though those values arent blank
// as I checked in debugger
public static void main(String[] args) throws UnsupportedEncodingException
{
String xOr1 = ("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736");
String xOr = "z({zzz{{z-{z{z{{{}z*{y)~x~x~{{rzsz(";
String result = "";
System.out.println("xOr1 length is " + xOr1.length());
String output = "";
byte[] encoded = xOr1.getBytes();
byte[] decoded;
String sub;
String matches = "(.*)abdef0123456789(.*)";
int hexInt;
for(int k = 0; k< 256;k++)
{
decoded = new byte[encoded.length];
result = "";
System.out.println(k);
for(int j = 0; j<encoded.length; j++)
{
decoded[j] = (byte)((int)encoded[j] ^ k);
result = Arrays.toString(decoded);
}
output = new String(decoded,"UTF-8");
//System.out.println(output);
try
{
for(int i = 0; i< output.length() -2; i++)
{
hexInt = Integer.parseInt(output,16);
System.out.println("You aren't dumb... " + output);
}
}
catch(NumberFormatException nfe)
{
//System.out.println(output);
System.out.println("bad boy");
}
}
}

How to loop in the file of array byte

public byte[][] createShares(byte[] secret, int shares, int threshold, Random rnd)
{
// some code here
}
I have this method and i am going to apply SSS for file of byte array .
byte [] secret is method parameter where i am going to pass as argument each byte of the file and then apply for each byte the SSS algorithm. I have also implemented a java code of how to read the file and then convert it to a byte array. I am stuck of how to implement this SSS algorithm for each byte of files.
I know i need a for loop for that . The point is i want to call to my main method this byte [] secret and assign to it each byte of the file but i am stuck of how to do it .
My method which will read the file and convert it to the array of bit is as below:
public byte[] readFile(File fileName) throws IOException {
InputStream is = new FileInputStream(fileName);
// Get the size of the file
long length = fileName.length();
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
throw new IOException("Could not completely read file " + fileName.getName() + " as it is too long (" + length + " bytes, max supported " + Integer.MAX_VALUE + ")");
}
// Create the byte array to hold the data
byte[] secret = new byte[(int)length];
int offset = 0;
int numRead = 0;
while (offset < secret.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < secret.length) {
throw new IOException("Could not completely read file " + fileName.getName());
}
// Close the input stream and return bytes
is.close();
return secret;
}
Can anyone help me how to loop for each byte of the file and then pass it as the argument to my createshares method ?
I understand you are trying to read bytes from the file and also trying to loop through the byte[].
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;
import java.nio.file.Path;
public class SSSAlgorithm {
public static void main(String[] args) {
System.out.println("Reading file");
try {
byte[] secret = readFile();
createShares(secret, 2, 3, 100);
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[][] createShares(byte[] secret, int shares, int threshold, int i)
{
// some code here
for (byte coeff : secret){
System.out.println("Use the byte here " + coeff);
}
return null;
}
public static byte[] readFile() throws IOException {
Path path = Paths.get("/Users/droy/var/crypto.txt");
try {
byte[] secret = Files.readAllBytes(path);
return secret;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
**Output:
Stored secret as 1234
byte array representation: [49, 50, 51, 52, 10]
Use the byte here 49
Use the byte here 50
Use the byte here 51
Use the byte here 52
Use the byte here 10

Convert Base64 to Binary String in Java

I have the following 3 byte encoded Base64 string.
String base64_str = "MDQw";
System.out.println("base64:" + base64_str);
String hex = DatatypeConverter.printHexBinary(DatatypeConverter.parseBase64Binary(base64_str));
for (int i = 0; i < hex.length(); i+=6) {
String bytes = hex.substring(i, i+6);
System.out.println("hex: " + bytes);
StringBuilder binary = new StringBuilder();
int byte3_int = Integer.parseInt(bytes.substring(4, 6), 16);
String byte3_str = Integer.toBinaryString(byte3_int);
byte3_int = Integer.valueOf(byte3_str);
binary.append(String.format("%08d", byte3_int));
int byte2_int = Integer.parseInt(bytes.substring(2, 4), 16);
String byte2_str = Integer.toBinaryString(byte2_int);
byte2_int = Integer.valueOf(byte2_str);
binary.append(String.format("%08d", byte2_int));
int byte1_int = Integer.parseInt(bytes.substring(0, 2), 16);
String byte1_str = Integer.toBinaryString(byte1_int);
byte1_int = Integer.valueOf(byte1_str);
binary.append(String.format("%08d", byte1_int));
System.out.println("binary: " + binary);
}
}
My Output is:
base64:MDQw
hex: 303430
binary: 001100000011010000110000
The above output is correct, but is there a more efficient way on converting a base64 string to binary string?
Thanks in advance.
You can use BigInteger (import java.math.BigInteger;) to convert a base64 string to binary string.
byte[] decode = Base64.getDecoder().decode(base64_str);
String binaryStr = new BigInteger(1, decode).toString(2);
Here is a small code to perform your operation. The only flaw is the use of replace for padding the 0.
import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
public class main {
public static void main(String [] args) throws UnsupportedEncodingException {
String base64_str = "MDQw";
byte[] decode = DatatypeConverter.parseBase64Binary(base64_str);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < decode.length; i++){
String temp = Integer.toBinaryString(decode[i]);
sb.append(String.format("%8s", temp).replace(" ", "0"));
}
System.out.println(sb.toString());
}
}

Convert Hex to Byte with big string

I tried the different ways to convert hex to byte, there are four methods in the code, three of them I comment it out, only one there is no error when I run it, but I confused that when I repeated to run the code, it gave me the different result (should be generate "byte").
There is a question is when I use "method1", it gave me the result (byte), but once I changed to "method2", it will not generate the result, I don't know why. I thought it should generate same result, when I have same string.
public class Convert {
/**
* #param args
* #throws IOException
*/
// String everything;
public static void main(String[] args) throws IOException {
//String everything;
// TODO Auto-generated method stub
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:\\TEMP1\\Doctor.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null) {
sb.append(line);
sb.append('\n');
line = br.readLine();
}
//*********Method 1****************
//String r="1ee079746828d7c6f9af46f93c1ef2555ff4b14b2378ad53a258d18dc6a8363fb57f3448783833722bd9ef291ba53153afca31a96de404755e78f68b76fd5a77e4be3b984ea25244842e92a8ed40da1f1a588fb3da26b8bc21d74cd8476534f26ee454df086567c4d7cf3334f794cede41a9b051a5c393a35584afcf";
//byte[] b = new BigInteger(r,16).toByteArray();
//System.out.println("Byte for public key: "+b);
//*********Method 2****************
//String r2 = sb.toString();
//System.out.println("Doctor contect file: "+r2);
//byte[] b = new BigInteger(r2,16).toByteArray();
//System.out.println("Byte for public key: "+b);
//********Method 3*****************
String r="1ee079746828d7c6f9af46f93c1ef2555ff4b14b2378ad53a258d18dc6a8363fb57f3448783833722bd9ef291ba53153afca31a96de404755e78f68b76fd5a77e4be3b984ea25244842e92a8ed40da1f1a588fb3da26b8bc21d74cd8476534f26ee454df086567c4d7cf3334f794cede41a9b051a5c393a35584afcf";
int len = r.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(r.charAt(i), 16) << 4)
+ Character.digit(r.charAt(i+1), 16));
System.out.println(data);
}
//********Method4******************
/*
String r2 = sb.toString();
int len = r2.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(r2.charAt(i), 16) << 4)
+ Character.digit(r2.charAt(i+1), 16));
System.out.println(data);
}
*/
//String r=everything;
// String r="1ee079746828d7c6f9af46f93c1ef2555ff4b14b2378ad53a258d18dc6a8363fb57f3448783833722bd9ef291ba53153afca31a96de404755e78f68b76fd5a77e4be3b984ea25244842e92a8ed40da1f1a588fb3da26b8bc21d74cd8476534f26ee454df086567c4d7cf3334f794cede41a9b051a5c393a35584afcf";
// double convert=Double.parseDouble(r);
// long convert=(long)(Integer.parseInt(r,32)&0xFF);
// byte convert=Byte.parseByte(r,32);
// byte convert=Integer.parseInt(everything,16);
// System.out.println("Byte for public key: "+convert);
} finally {
br.close();
}
}
}
You're printing the result of calling toString on a byte[]. That's not going to give you what you want.
For diagnostic purposes, use System.out.println(Arrays.toString(data)). And do that at the end of the loop rather than within it:
for (int i = 0; i < len; i += 2) {
...
}
System.out.println(Arrays.toString(data));
There are plenty of alternative approaches to parsing a hex string, mind you. I don't personally like the idea of using an XML-focused API (as recommended in the question comments) when you're not dealing with XML, but it would certainly work - and any number of third party APIs have hex conversion routines.
EDIT: As noted in comments, I believe your hex conversion code is also broken at the moment - but that should probably be fixed by using a prebuilt one from elsewhere. The main purpose of this answer was to explain why you're getting results such as "[B#40a0dcd9". Once you can see the data, you can verify it.
I'm unsure on why you do that, so this answer may not reflect your intend.
I tried to comprehend your stuff and came to the conclusion that you want to split that string into two character blocks, treat them as a hex number and convert them to a byte.
That wont work, as the second block e0 is larger that Byte.MAX_VALUE. So, heres my latest guess on what could be the code that you are looking for (using Integer).
public static void main(String[] args) {
String r = "1ee079746828d7c6f9af46f93c1ef2555ff4b14b2378ad53a258d18dc6a8363fb57f3448783833722bd9ef291ba53153afca31a96de404755e78f68b76fd5a77e4be3b984ea25244842e92a8ed40da1f1a588fb3da26b8bc21d74cd8476534f26ee454df086567c4d7cf3334f794cede41a9b051a5c393a35584afcf";
char[] rA = r.toCharArray();
int len = r.length();
int[] data = new int[len / 2];
for (int i = 0; i < len; i += 2) {
String base = "#" + rA[i] + rA[i+1];
System.out.println("base: " + base);
data[i / 2] = Integer.decode(base);
System.out.println(data[i/2]);
}
}
After reading your question again, it seems that you describe that when you use the String directly (method1) it works, but if you read if from a file (method2) it does not.
The reason is simple: You add a \n at the end of the String you read from file. You do not do so in your method1.

Categories

Resources