I use this code for encryption and decryption.
I am currently hexing my bytes after I encrypt them.
How can I unhex/convert to readable/original string?
I keep getting this:
Encrypted [B@18eb9e6
Encrypted with hex formatting d8ba7ec8e56f50098cabc53508a84f5a
Hello World
d8ba7ec8e56f50098cabc53508a84f5a
��~��oP ���5�OZ
package mybeans;
import javax.crypto.*;
import javax.crypto.spec.*;
import org.apache.commons.codec.binary.Base64;
public class Test2 {
public static void main(String[] args) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(
"05468345670abcde".getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec("f45gt7g83sd56210"
.getBytes());
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encrypted = cipher.doFinal("Hello World".getBytes());
System.out.println("Encrypted "+encrypted);
System.out.println("Encrypted with hex formatting "+asHex(encrypted));
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println(originalString);
String g = asHex(encrypted);
System.out.println(g);
String gg = unHex(g);
System.out.println(gg);
}
public static String asHex(byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static String unHex(String hex){
byte[] bytes = new byte[hex.length()/2];
for(int i=0;i<bytes.length;i++){
bytes[i] = (byte)Integer.parseInt(hex.substring(2*i, 2*i+2),16);
}
String multi = new String(bytes);
return multi;
}
}