Question

I get this error(in the title). I am not sure why, help, please. 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;


}   

Edit. In the end i managed this problem using public key file with .der extension (before it was .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 "divanov" answered the question i was asking.

Was it helpful?

Solution

Exception error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag means that result of

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

doesn't represent ASN.1 DER encoded message. Print it somewhere as hex to verify what is an exact problem

Log.v("HEX", org.apache.commons.codec.binary.Hex.encodeHexString(pubKeyBytes);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top