解码南非za-drivers-license

时间:2017-03-16 10:26:41

标签: java android encryption rsa public-key

参考此讨论:Decode South African (ZA) Drivers License

请帮助我似乎在尝试在Android上用Java创建PublicKey实例时遇到错误。我已粘贴以下错误:

java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag

以下是代码段:

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]);

1 个答案:

答案 0 :(得分: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以获得替代方案的相同问题。