**问题标题:**服务端是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);
}
乱码返回
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。