adamchenk1
adamchenk1
采纳率0%
2017-08-24 05:47 阅读 2.6k

安卓RSA私钥解密 出现乱码

最近遇到了1个奇葩的项目需求,需要在安卓客户端做RSA私钥解密的工作,写了代码以后发现一直输出乱码

```public class RSAUtils {
/**
* load private key from a stream
*
* @param
* @return
* @throws Exception
*/

private static final int MAX_DECRYPT_BLOCK = 256;


private static RSAPrivateKey loadPrivateKey(InputStream in) throws Exception {
    RSAPrivateKey priKey;
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String readLine = null;
        StringBuilder sb = new StringBuilder();
        while ((readLine = br.readLine()) != null) {
            if (readLine.charAt(0) == '-') {
                continue;
            } else {
                sb.append(readLine);
                sb.append('\r');
            }
        }
        byte[] priKeyData = Base64.decode(new String(sb), Base64.DEFAULT);


        PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(priKeyData);
        KeyFactory keyFactory= KeyFactory.getInstance("RSA");
        priKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (IOException e) {
        throw new Exception("error reading the key");
    } catch (NullPointerException e) {
        throw new Exception("inputstream is null");
    }
    return priKey;
}


/**
 * decrypt with a private key
 *
 * @param privateKey
 * @param cipherData
 * @return
 * @throws Exception
 */
private static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
    if (privateKey == null) {
        throw new Exception("key is null");
    }
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        int inputLen = cipherData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(cipherData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(cipherData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;

    } catch (NoSuchAlgorithmException e) {
        throw new Exception("no such algorithm");
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        return null;
    } catch (InvalidKeyException e) {
        throw new Exception("InvalidKeyException");
    } catch (IllegalBlockSizeException e) {
        throw new Exception("IllegalBlockSizeException");
    } catch (BadPaddingException e) {
        throw new Exception("BadPaddingException");
    }
}

public static String RSADecrypt(Context context, String KeyFileNameInAssetFolder, byte[] content) {
    String result = "error";
    try {
        InputStream inputStream = context.getResources().getAssets().open(KeyFileNameInAssetFolder);
        RSAPrivateKey privateKey = loadPrivateKey(inputStream);
        byte[] b = decrypt(privateKey, content);
        result = new String(b);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
调用的时候  我调了

String result = RSAUtils.RSADecrypt(getApplicationContext(),"pkcs8.pem",Base64.decode(s,Base64.DEFAULT));


然后输出的一直是
��*�ۘˋ��Ӡ���b$�<Ni����E�Dν��Y��u��Z߱���C�$i�3��yDŽS�bI.E�lI�Cq\}e|=xc�t���%�̳��(�>�`�����=ݞ*��6̞Q;��D��ffd��W�J: �������C�tG���r�=�5�n����#a�x��٠���^��l�Y�ث�2��#�j�\��.^�N�y�`�6_X੒J��,�8�ԑDw�tpV�|<Zܕ~�$u���������#���U�)�3�0ͧ%�K��>\5[�H�D�4��I�
类似这种东西  不这i到哪里错了 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • oSpongeBob123 oSpongeBob123 2019-07-05 23:00
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    
    点赞 1 评论 复制链接分享
  • forest_open forest_open 2017-08-24 07:26

    建议你先看下byte[] b = decrypt(privateKey, content);这句话结果对不对,然后result = new String(b);这里有一个强制转换我觉得是有问题的。

    点赞 评论 复制链接分享

相关推荐