使用Java将ASN1序列解码为RSA公钥 [英] Decode ASN1 sequence to RSA public key using Java
问题描述
我有以下RSA公钥作为ASN1序列:
I have the following RSA public key as ASN1 sequence:
SEQUENCE(2 elem)
INTEGER (1024 bit) 14832…
INTEGER 65537
如何将此序列作为RSA公钥导入Java的?实现的 KeySpec
s(例如 PKCS8EncodedKeySpec
)不起作用(显然)。
How can I import this sequence as RSA public key in Java? The implemented KeySpec
s (such as PKCS8EncodedKeySpec
) do not work (obviously).
此外,我尝试使用BouncyCastle并手动解码序列并自行初始化 java.security.spec.RSAPublicKeySpec
。然而,这种方法似乎相当笨拙。
In addition I tried to use BouncyCastle and manually decode the sequence and initialize java.security.spec.RSAPublicKeySpec
myself. However this approach seems rather clumsy.
有更简单的方法吗?
推荐答案
您可以使用Bouncycastle库,如下面的代码片段所示:
You can use the Bouncycastle library as in the following code fragment:
import java.io.IOException;
import java.math.BigInteger;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DLSequence;
public class RsaAsn1Example {
// ...
public static BigInteger [] parseASN1RsaPublicKey(byte [] encoded) throws IOException {
ASN1InputStream asn1_is = new ASN1InputStream(encoded);
DLSequence dlSeq = (DLSequence) asn1_is.readObject();
ASN1Integer asn1_n = (ASN1Integer) dlSeq.getObjectAt(0);
ASN1Integer asn1_e = (ASN1Integer) dlSeq.getObjectAt(1);
asn1_is.close();
return new BigInteger[]{ asn1_n.getPositiveValue(), asn1_e.getPositiveValue()};
}
// ....
}
或,作为一个不那么有吸引力的替代方案,你可以像这个例子来自我的一个答案。但要注意,ASN.1解码可能非常棘手 - 这个非常简单的两个元素序列是关于我试图用我自己的代码解析的最复杂的ASN.1结构。
Or, as a less attractive alternative, you can roll you own ASN.1 decoder as in this example from one of my answers. But beware, ASN.1 decoding can be very tricky -- this very simple two element sequence is about the most complicated ASN.1 structure I would ever attempt to parse with my own code.
这篇关于使用Java将ASN1序列解码为RSA公钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!