【发布时间】:2014-01-06 18:45:33
【问题描述】:
我尝试使用 HTTPWebRequest 在 C# 和 PHP 之间交换 AES 密钥:
// This is to send the request to php using UTF8
public string SendRequest(Uri path, NameValueCollection nvc)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path);
byte[] input = Encoding.UTF8.GetBytes(GetPostString(nvc));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = input.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(input, 0, input.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
return result;
}
// That's a piece of code of how i try to send the C#'s public key to php:
string result = SendRequest(builder.Uri, publicKeyNVC);
string[] parts = Regex.Split(result, "</seperator>");
this.cryptoHelper.ExchangedAESKey = this.cryptoHelper.DecryptRSA(parts[0]);
this.cryptoHelper.ExchangedAESIV = this.cryptoHelper.DecryptRSA(parts[1]);
这是我的 exchange-php-file 的重要部分:
$key = md5(uniqid());
$size = mcrypt_get_iv_size(MCRYPT_CAST_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
$rsa = new Crypt_RSA();
$public = str_replace('</RSAKeyValue>', '<P></P><Q></Q><DP></DP><DQ></DQ><InverseQ></InverseQ><D></D></RSAKeyValue>', $public_key);
$rsa->loadKey($public, CRYPT_RSA_PRIVATE_FORMAT_XML);
$rsa->loadKey($rsa->getPublicKey());
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext_key = ($rsa->encrypt($key));
$ciphertext_iv = ($rsa->encrypt($iv));
echo ($ciphertext_key."</seperator>".$ciphertext_iv);
echo "</seperator>".$key."|".strlen($ciphertext_key)."|".strlen($ciphertext_iv);
很抱歉发布了这么多代码,但我不能确定我的错误隐藏在哪里。我的问题是,php要求的长度是
echo "</seperator>".$key."|".strlen($ciphertext_key)."|".strlen($ciphertext_iv);
(128) 的长度与我收到的响应不同。 DecryptRSA(parts[0]) 中的响应已用 UTF8 解码,超过 200 个字节,因此 RSADecrypt-Method 当然会出错。
【问题讨论】: