从磁盘加载存储RSA公钥/私钥? [英] Load stored RSA public/private key from disk?

查看:268
本文介绍了从磁盘加载存储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 实例恢复< A HREF =htt​​p://docs.oracle.com/javase/6/docs/api/java/security/PublicKey.html相对=nofollow>公钥和的 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.

这篇关于从磁盘加载存储RSA公钥/私钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆