java.lang.RuntimeException:错误:0D0680A8:asn1编码例程:ASN1_CHECK_TLEN:错误的标记

我收到此错误(在标题中).我不确定为什么,请帮忙.代码如下:

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 "";   

但是“迪瓦诺夫”回答了我提出的问题.

最佳答案 异常错误:0D0680A8:asn1编码例程:ASN1_CHECK_TLEN:错误的标记意味着结果

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);
点赞