4

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.

Mikelis Kaneps
  • 4,576
  • 2
  • 34
  • 48

1 Answers1

2

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);
divanov
  • 6,173
  • 3
  • 32
  • 51
  • The response string was 3082040d308202f5a003020102020900faebd97c3cbce29d300d06092a864886f70d010105050030819c310b3009060355040613025553310b...and something like that, what can I tell from this? – Mikelis Kaneps Apr 04 '14 at 09:03
  • 1.2.840.113549.1.1.5 is OID for sha1-with-rsa-signature while public key OID should be 1.2.840.113549.1.1.1. Plus it's not ASN.1 DER. It looks like this is public key certificate rather than public key in X.509 encoding. – divanov Apr 04 '14 at 13:58
  • There is no such method in andorid `Hex.encodeHexString` – Sirop4ik Oct 22 '17 at 12:46
  • Could you take a look at this SO question https://stackoverflow.com/questions/46812752/error0c0890baasn-1-encoding-routinesasn1-check-tlenwrong-tag – Sirop4ik Oct 22 '17 at 12:47