import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class byte2hexandhex2byte {
// Convert Hex String to Byte Array
public static byte[] hex2byte(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(str.substring(2 * i, 2 * i + 2), 16);
}
return bytes;
}
// Convert Byte Arrary to Hex String
public static String byte2hex(byte[] b) {
// String Buffer can be used instead
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
if (n < b.length - 1) {
hs = hs + "";
}
}
return hs;
}
private static byte[] getSalt() throws NoSuchAlgorithmException {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return salt;
}
public static void main(String[] args) throws NoSuchAlgorithmException {
byte[] a = getSalt();
System.out.println(byte2hex(a));
System.out.println(byte2hex(hex2byte(byte2hex(a))));
}
}