我收到此错误(在标题中)。我不知道为什么,请帮助。代码如下:

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;


}

编辑。最后,我使用带有 .der 扩展名的公钥文件(在它是 .crt 之前)解决了这个问题,并且有效的代码是:
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 "";

但是“divanov”回答了我提出的问题。

最佳答案

异常 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag 意味着结果

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

不代表 ASN.1 DER 编码的消息。将其以十六进制形式打印在某处以验证确切的问题是什么
Log.v("HEX", org.apache.commons.codec.binary.Hex.encodeHexString(pubKeyBytes);

关于java.lang.RuntimeException : error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22842235/

10-11 01:32