问题
independent from the fact that the private key should be encrypted (which happens independently from this question): I'm generating RSA key pairs using this code:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
privKey = (RSAPrivateKey)keyPair.getPrivate();
pubKey = (RSAPublicKey)keyPair.getPublic();
byte[] data=privKey.getEncoded();
...
byte[] data=pupKey.getEncoded();
The contents of data are binary and not Base 64 encoded or something like that.
When I store the contents of data somewhere and want to load them later - how can I do that? RSAPrivateKey and RSAPublicKey do not have any constructors/loader or something like that...
回答1:
It's confusing, but to go from a java Key to bytes for storage use the getEncoded() method. To go the other way, from bytes to a Key, use a KeyFactory.
If your key is a private key, then to go from bytes back to a private key create a PKCS8EncodedKeySpec. To go from bytes to an RSA public key use an X509EncodedKeySpec. These KeySpecs are then supplied to an instance of an appropriate KeyFactory to recover the PublicKey and PrivateKey objects.
来源:https://stackoverflow.com/questions/19366498/load-stored-rsa-public-private-key-from-disk