引用此讨论:Decode South African (ZA) Drivers License
请协助我尝试在 Android 上的 Java 中创建 PublicKey 实例时似乎遇到错误。我已粘贴以下错误:
java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
这是代码 fragment :
Cipher asymmetricCipher = null;
asymmetricCipher = Cipher.getInstance("RSA");
X509EncodedKeySpec publicKeySpec128 = new X509EncodedKeySpec(key128block);
X509EncodedKeySpec publicKeySpec74 = new X509EncodedKeySpec(key74block);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
Key key = keyFactory.generatePublic(publicKeySpec128);
asymmetricCipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainText = asymmetricCipher.doFinal(topBlocksData[0]);
您尝试读取的编码公钥不符合 X509EncodedKeySpec
预期的格式。相反,它们具有更简单的形式,不幸的是,Java 不支持这种形式。但是,您可以使用 BouncycaSTLe 或 SpongycaSTLe 库编写一个小型 java 例程来解析这些值。下面的代码复制自my answer至 this question .
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()};
}
// ....
}
parseASN1RsaPublicKey
返回的值可以提供给 RsaPublicKeySpec
构造函数来创建公钥。
另请检查divanov's answer相同的问题以寻求替代方案。
我是一名优秀的程序员,十分优秀!