· 7 years ago · Sep 03, 2018, 08:46 PM
1Problem when converting bytes [] to string, then back to byte[]
2public class test {
3 public static String asHex (byte buf[]) {
4 StringBuffer strbuf = new StringBuffer(buf.length * 2);
5 int i;
6
7 for (i = 0; i < buf.length; i++) {
8 if (((int) buf[i] & 0xff) < 0x10)
9 strbuf.append("0");
10
11 strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
12 }
13
14 return strbuf.toString();
15 }
16
17 public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
18
19
20 KeyGenerator kgen = KeyGenerator.getInstance("AES");
21kgen.init(128);
22
23SecretKey skey = kgen.generateKey();
24byte[] raw = skey.getEncoded();
25
26String r = new String(raw,"UTF-8");
27
28System.out.println(asHex(raw));// prints for example fd812245c9bfc4106294d51bf27e3796
29
30byte[] t = r.getBytes("UTF-8");
31
32System.out.println(asHex(t)); // prints for example : efbfbd2245c9bfefbfbd1062efbfbdefbfbd1befbfbd7e37efbfbd
33
34 }
35}