我有以下RSA公钥作为ASN1序列:

SEQUENCE(2 elem)
  INTEGER (1024 bit) 14832…
  INTEGER 65537

如何在Java中将此序列作为RSA公钥导入?实现的KeySpec(例如PKCS8EncodedKeySpec)不起作用(显然)。

另外,我尝试使用BouncyCastle并手动解码序列并自己初始化java.security.spec.RSAPublicKeySpec。但是,这种方法似乎很笨拙。

有更容易的方法吗?

最佳答案

您可以像下面的代码片段中那样使用Bouncycastle库:

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()};
    }
// ....
}

或者,作为一种不太吸引人的替代方法,您可以从我的答案之一中像this example中一样滚动自己的ASN.1解码器。但是请注意,ASN.1解码可能非常棘手-这个非常简单的两元素序列涉及我尝试用自己的代码解析的最复杂的ASN.1结构。

07-24 09:45
查看更多