@
eabet 不是 JSON 数据的问题, 而是你的源数据串太长.
就像 4 楼 @
zhouheyang0919 说的那样, 不能加密太长的数据.
附完整的测试代码:
```
<?php
$public_key = '
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6BzEdnKKNifTOGk33p8+Sp4En
OEsprSqbsTZgVRDmg2aLP5XhhSBlu4PPurMEz2W0tj1TyhkfJvdtkHuA629/760g
HExMOaNHzJdwvkTJW7ZlBi4+KoI0F/48Y4i71kuXY6V6niIZjzypnEfMPyo2+CCE
d1VeXOFqnjYmOHsG0wIDAQAB
-----END PUBLIC KEY-----
';
$private_key = '
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC6BzEdnKKNifTOGk33p8+Sp4EnOEsprSqbsTZgVRDmg2aLP5Xh
hSBlu4PPurMEz2W0tj1TyhkfJvdtkHuA629/760gHExMOaNHzJdwvkTJW7ZlBi4+
KoI0F/48Y4i71kuXY6V6niIZjzypnEfMPyo2+CCEd1VeXOFqnjYmOHsG0wIDAQAB
AoGALhD7265fHpesFKG07wASSenK9NBe5IoqQ/XFVmOaVMrzSMZNMlSKKkceJAHC
tQ06zV5Xn3krcWhv2yTtQIaMzH/LAqNvisGrS8W5S/i9rGECXINNmmym0yYzHyvW
TrTuFvABiO9jAPe7a26hY2SibJ7/rbRykxmm69EvimuKoakCQQD2JpR8dcgEmqNk
q+m4RifXDFet5grvjX/6Ow9Cb+ZnUDKu1jEmqtebBorVFka3adCfcmyaeVQvol4D
4pDVne3dAkEAwXjAfhgSNBYjUzkgLMHuBztPDMDQbqjtZGEeKQIUJetCKMI2CLdH
luqfRjHSKUBC/Vu5j/i1axCubdJeBHA0bwJAOrVi7vhsl2SGmglCulfJQspH00st
yor2Pil97zufOX7wR7EAkhdnSytZS49/mFldj9oLuyA7Cw1v3P9Zyglb5QJAZG1s
5kdSc60mKxYVKIaGK0TTFNilmTug9qEfCcRldwV2szeU2tNgmusxQDuuTvFnlKJf
YWeFrIzdLm6rlPw1iwJBAKM33BIVC1QSRHrpC1kUHGPFSC7R2ISaT8Mjfh/shRn9
Lmsv3CzXRPZRfxxt4fyYp8rIllo97Gd/xWWNAMlnXBQ=
-----END RSA PRIVATE KEY-----
';
$pi_key = openssl_pkey_get_private($private_key);
$pu_key = openssl_pkey_get_public($public_key);
$terId = 1111111111;
$businessOrdid = 222222222;
$orderName = '$orderName 带空格,带汉字,带,全半角内容';
$Gold = 100;
$selfParam = '234lkajsdfasdf';
$syncURL = '
http://test.com/sync';$asynURL = '
http://test.com/async';$payType = 'test';
$encrypted = '';
$json = array();
$json['terId'] = $terId;
$json['businessOrdid'] = $businessOrdid;
$json['orderName'] = $orderName;
/*
$json['tradeMoney'] = $Gold;
$json['selfParam'] = $selfParam;
$json['syncURL'] = $syncURL;
$json['asynURL'] = $asynURL;
$json['payType'] = $payType;
$json['appSence'] = '1001';
*/
$data = json_encode($json, JSON_UNESCAPED_UNICODE);
$r = openssl_public_encrypt($data, $encrypted, $pu_key);//公钥加密
if($r === FALSE){
echo "加密失败!";
die();
}
$encrypted = base64_encode($encrypted);
echo $encrypted,"\n";
echo "private key decrypt:\n";
openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key);//私钥解密
echo $decrypted,"\n";
```
把上面代码里注释的那部分数据打开, 你就会发现它会加密失败.