Java.lang.RuntimeException: error: 0D0680A8: asn1 encoding procedure: ASN1_CHECK_TLEN: invalid tag

I get this error (in the header). I don’t know why, please help. Code below:

public static String decryptRSA(Context mContext, byte[] message) throws Exception { 


    InputStream in = mContext.getResources().openRawResource(R.raw.publicrsakey);
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(org.apache.commons.io.IOUtils.toByteArray(in));

    PublicKey publicKey = 
            KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec);

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    final String encryptedString = Base64.encode(cipher.doFinal(message));

    return encryptedString;


}   

Change In the end, I dealt with this problem using a public key file with the extension .der (before its .crt), and the code that worked was:

InputStream in = mContext.getResources().openRawResource(R.raw.key);

        CertificateFactory cf = CertificateFactory.getInstance("X509");
        Certificate cert = cf.generateCertificate(new ByteArrayInputStream(org.apache.commons.io.IOUtils.toByteArray(in)));
        PublicKey pubKey = cert.getPublicKey();
        try
        {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");            
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            final String encryptedString = Base64.encode(cipher.doFinal(message));
            return encryptedString;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return "";   

But the “sofas” answered the question that I asked.

+4
source share
1 answer

The exception error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tagmeans that the result

InputStream in = mContext.getResources().openRawResource(R.raw.publicrsakey);
byte[] pubKeyBytes = org.apache.commons.io.IOUtils.toByteArray(in);

does not represent an ASN.1 DER encoded message. Print it somewhere as hex to check what the exact problem is.

Log.v("HEX", org.apache.commons.codec.binary.Hex.encodeHexString(pubKeyBytes);
+2

Source: https://habr.com/ru/post/1534863/


All Articles