Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Convert from hex to readable string

843811Jun 5 2008 — edited Jun 9 2008
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;
	}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 7 2008
Added on Jun 5 2008
12 comments
1,046 views