javax.crypto.SecretKey is binary data, so you cannot convert it directly to a string. You can encode it as the sixth line or in Base64.
See Apache Commons Codec .
Update. If you do not want to depend on third-party libraries (and cannot / do not want to store simple binary data, as John suggests), you can do some ad-hoc encoding, for example, after the erickson sentence:
public static String bytesToString(byte[] b) { byte[] b2 = new byte[b.length + 1]; b2[0] = 1; System.arraycopy(b, 0, b2, 1, b.length); return new BigInteger(b2).toString(36); } public static byte[] stringToBytes(String s) { byte[] b2 = new BigInteger(s, 36).toByteArray(); return Arrays.copyOfRange(b2, 1, b2.length); }
It is rather ugly, non-standard and not optimal (in terms of output). But he is also very small, correct and has no dependencies; this can be practical, especially if your data is small.
Updated: I replaced Character.MAX_RADIX with a literal value (36), following GregS comment. It may seem less elegant, but actually more secure. (You can also use 32 or 16).
source share