问题
I'm trying to implement the javax.crypto
encryption between my apps (through intnets). I follow this (accepted answer): https://stackoverflow.com/questions/4319496/how-to-encrypt-and-decrypt-data-in-java .The problem is as I understood I need to have the same SecretKeySpec key
in both of my apps in order to encrypt/decrypt the data. I have no idea how to export it (as a String or anything) and then hardcode it in both of my apps.
回答1:
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");
来源:https://stackoverflow.com/questions/20330494/how-to-export-symmetric-encryption-key