序列化和反序列化RSA公钥 [英] Serialize and Deserialize an RSA public key
问题描述
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();
我想从 byte []中创建公钥
。
我试过这个作为实验:
publicKey = new SecretKeySpec(publicKey.getEncoded(),publicKey.getAlgorithm());
但是使用该密钥解密则失败。
<我还尝试使用
ObjectOutputStream
序列化密钥,但序列化失败。
java.io.NotSerializableException:org.apache.harmony.xnet.provider.jsse.OpenSSLKey
我读了这里我无法使用使用RSA的SecretKeySpec
。
所以只要您谈论的是SecretKey而不是RSA或DSA关键,那么你不必经历涉及KeyGenerator等的任何扭曲。
任何人都知道如何执行这些扭曲或这样做。
来自RSA的非对称密钥通常以X509格式存储。因此,您可以使用 X509EncodedKeySpec
。
一个简单的例子已经在Java 7 JavaDoc中了(只需用DSA代替DSA):
http://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);
如果你需要从 byte [] $ c反序列化私有$ c>,我发现你必须使用
PKCS8EncodedKeySpec
。
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();
I want to create just the public key from a byte[]
.
I have tried this as an experiment:
publicKey = new SecretKeySpec(publicKey.getEncoded(), publicKey.getAlgorithm());
But decryption using that key then fails.
I have also tried serializing the key with ObjectOutputStream
, but serialization fails.
java.io.NotSerializableException: org.apache.harmony.xnet.provider.jsse.OpenSSLKey
I read here that I can't use SecretKeySpec
with RSA.
so as long as you are talking of a SecretKey and not an RSA or DSA key then you don't have to go through any contortions involving KeyGenerator or the like.
Anyone know how to perform these contortions or a way of doing this.
Asymmetric keys like those from RSA are usually stored in X509 format. Therefor you can use X509EncodedKeySpec
instead.
A simple example is already in the Java 7 JavaDoc (just replace DSA with RSA): http://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);
If you need to deserialize the private from byte[]
, I've found that you must use PKCS8EncodedKeySpec
.
这篇关于序列化和反序列化RSA公钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!