Android Rsa解密出现乱码问题

本文介绍了一种使用Java实现的RSA私钥解密方法,并针对Android平台出现的乱码问题提出了解决方案,即通过指定Cipher的转换模式为RSA/ECB/PKCS1Padding来避免乱码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Rsa 私钥解密

通常java 解密方法如下


    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) {
        //64位解码加密后的字符串
        String outStr = null;
        try {

//
            byte[] inputByte = Base64.getDecoder().decode(str);
            //base64编码的私钥

            byte[] decoded = Base64.getDecoder().decode(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            outStr = new String(cipher.doFinal(inputByte), StandardCharsets.UTF_8);

          

        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "decypt exception is" + e.getMessage());
        }
        return outStr;
    }

如果Android 用这种方式创建Cipher 的话 会出现乱码
解决:

  Cipher cipher = Cipher.getInstance("RSA"); 

替换成

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

完美解决!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值