Skip to content
Advertisement

decode south african za-drivers-license

In reference to this discussion: Decode South African (ZA) Drivers License

Please assist I seem to be getting an error trying to create PublicKey instance in Java on android. I have pasted the error below:

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

Here is the code snippet:

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

Advertisement

Answer

The encoded public keys you’re trying to read are not of the format expected by X509EncodedKeySpec. Instead they are of an even simpler form which, unfortunately, is not supported by Java. However, you can use the Bouncycastle or Spongycastle library to code up a small java routine to parse the values. The code below is copied from my answer to 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()};
    }
// ....
}

The values returned by parseASN1RsaPublicKey can be supplied to an RsaPublicKeySpec constructor to create the public key.

Also examine divanov’s answer to the same questions for an alternative.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement