In the similar question “Conversion of byte[] into a String and then back to a byte[]” is said to not to do the byte[] to String and back conversion, what looks like apply to most cases, mainly when you don’t know the encoding used.
But, in my case I’m trying to save to a DB the javax.crypto.SecretKey data, and recoverd it after.
The interface provide a method getEncoded() which returns the key data encoded as byte[], and with another class I can use this byte[] to recover the key.
So, the question is, how do I write the key bytes as String, and later get back the byte[] to regenerate the key?
javax.crypto.SecretKeyis binary data, so you can’t convert it directly to a String. You can encode it as a hex string or in Base64.See Apache Commons Codec.
Update: If you dont want to depend on third-party libraries (and can’t/don’t want to store plain binary data, as Jon suggests) you can do some ad-hoc encoding, for example, following erickson’s suggestion:
It’s rather, ugly, non-standard and not optimal (in output size). But it’s also very small, correct and it has no dependencies; it can be practical, specially if your data is small sized.
Updated: I replaced the
Character.MAX_RADIXby the literal value (36), following GregS’s comment. It might seem less elegant but it’s actually more secure. (You can also use 32 or 16).