Load stored RSA public/private key from disk?

狂风中的少年 提交于 2020-01-14 05:37:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!