How to store a key pair inside a variable so that it will not change
How do I get this key pair out and store it so that it won't change and I will be able to use the same keypair to encrypt and decr开发者_C百科ypt in separate applications ? I am encrypting a string eg ("1234A") with the public key from this key pair and storing it into a database. For the decrypt part, I am getting the encrypted string out from the database and decrypting it using the private key from the same keypair.
public static KeyPair generateKey () throws NoSuchAlgorithmException
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance ("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
return key;
}
The KeyPair class implements Serializable, as do its component parts PrivateKey and PublicKey. You could serialize to a byte stream and store this in your database?
First you need to get the public and the private key from your KeyPair with:
PrivateKey priv = key.getPrivate();
PublicKey pub = key.getPublic();
This method will write the keys to a file, which you can later use to decrypt/verify in a separate application:
public void writeToFile(PrivateKey priv, PublicKey pub){
byte[] keyBytes = priv.getEncoded();
FileOutputStream privOut;
try {
privOut = new FileOutputStream(privateName);
privOut.write(keyBytes);
privOut.close();
FileOutputStream pubOut = new FileOutputStream(publicName);
byte[] pubKeyBytes = pub.getEncoded();
pubOut.write(pubKeyBytes);
pubOut.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
KeyPair
is serializable, so you might serialize it to a file or the db and deserialize it in all applications.
精彩评论