开发者社区> 问答> 正文

服务端是PHP RSA 私钥加密,在Java客户端 RSA 公钥解密,解密后有乱码

**问题标题:**服务端是PHP RSA 私钥加密,在Java客户端 RSA 公钥解密,解密后有乱码

提示:服务端和客户端都是用RSA算法加密解密的

//PHP服务端加密代码
    public static function encryptByPrivateKey($dataStr, $privateKey)
    {
        $dataStr      = self::str2utf8($dataStr);
        $privateKeyId = openssl_get_privatekey($privateKey);
        $data         = "";

        $dataArray = str_split($dataStr, self::PRIVATE_KEY_BITS / 8 - 11);
        foreach ($dataArray as $value) {
            openssl_private_encrypt($value,$encryptedTemp, $privateKeyId,self::EN_DE_ALGORITHM);
            $data .= $encryptedTemp;
        }
        openssl_free_key($privateKeyId);
        return base64_encode($data);
    }
//Java客户端解密代码

    static String decryptByPublicKey(String encryptedDataStr, String publicKey) throws Exception {
        byte[] encryptedData = Base64.decode(encryptedDataStr, Base64.DEFAULT);
        byte[] keyBytes      = Base64.decode(publicKey, Base64.DEFAULT);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

        cipher.init(Cipher.DECRYPT_MODE, publicK);
        int inputLen = encryptedData.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(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        Log.d(TAG,"decryptedData:" + decryptedData);
        return new String(decryptedData, ENCODING);
    }

乱码返回 QQ截图20230108142205.jpg

展开
收起
辰星大大 2023-01-08 14:25:41 344 0
1 条回答
写回答
取消 提交回答
  • GitHub https://github.com/co63oc/cloud

    数据分多段加密,加密后数据长度可能不同

    2023-01-14 20:54:26
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
PHP安全开发:从白帽角度做安全 立即下载
PHP 2017.北京 全球开发者大会——高可用的PHP 立即下载
复杂PHP系统性能瓶颈排查及优化 立即下载