从磁盘加载存储RSA公钥/私钥?
独立的事实,私钥应该被加密(从这个问题发生独立):我生成使用这个code RSA密钥对的:
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();
数据的内容是二进制,而不是基地64 EN codeD或类似的东西。
The contents of data are binary and not Base 64 encoded or something like that.
当我存储的数据内容的地方,并希望以后加载它们 - 我该怎么办呢? RSAPrivateKey和RSAPublicKey没有任何构造函数/装载机或类似的东西...
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...
这是令人困惑,但去的从的一个java的重点的到的存储使用的 getEn codeD()方法。走另一条路,从的字节到的一个的重点,使用的的KeyFactory 。
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.
如果您的密钥是私钥,然后去的从的字节回的到的私钥创建的 PKCS8En codedKeySpec 。去的从的字节到的RSA公钥使用的 X509En codedKeySpec 。这些 KeySpecs 然后提供给一个适当的的KeyFactory 实例恢复公钥和的 PrivateKey 对象。
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.