You can export a SecretKey
using the getEncoded()
method. This returns a byte array, which you could encode to a string, for example using base 64 encoding. The SecretKeySpec
object can be recreated from this encoded byte array.
Just to give you a better idea, not tested:
Initial generation and export
import org.apache.commons.codec.binary.Base64;
// "AES" is the key generation algorith, you might want to use a different one.
KeyGenerator kg = KeyGenerator.getInstance("AES");
// 256-bit key, you may want more or fewer bits.
kg.init(256);
SecretKey key = kg.generateKey();
byte[] keyBytes = key.getEncoded();
// Encode to a String, e.g. base 64 encoded
String encodedKey = new String(Base64.encodeBase64(keyBytes), "UTF-8");
Import/re-creation
// Base 64 decode
byte[] keyBytes = Base64.decodeBase64(encodedKey.getBytes("UTF-8"));
// Need to put the same key generation algorithm in here:
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");