.net到mono RSACryptoServiceProvider不工作
本文关键字:工作 RSACryptoServiceProvider mono net | 更新日期: 2023-09-27 18:04:09
我目前正在将我的一个库移植到mono,使其可用于MonoMac。我在这个库中使用RSA,它的工作方式不一样:它在。net Framework 4中工作得很好,但在mono中它不再工作了…
我使用RSA交换密钥,这里是服务器端代码:
private void SecureConnection()
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = RSA.ExportParameters(false);
NetStream.Write(RSAKeyInfo.Modulus, 0, RSAKeyInfo.Modulus.Length);
NetStream.Flush ();
byte[] keyReceived = new byte[128];
byte[] IvReceived = new byte[128];
int position = 0;
while (position < 127) {
position += NetStream.Read (keyReceived, position, 128 - position);
}
position = 0;
while (position < 127) {
position += NetStream.Read (IvReceived, position, 128 - position);
}
byte[] realKey = RSA.Decrypt(keyReceived, true);
byte[] realIv = RSA.Decrypt(IvReceived, true);
Rijndael = new RijndaelManaged { Key = realKey, IV = realIv };
Encrypt = Rijndael.CreateEncryptor();
Decrypt = Rijndael.CreateDecryptor();
FullName = WaitAndGetString();
Debug.WriteLine("[TCP] TcpHandler -> Connection to {0} ({1}) secured successfully", TcpClient.RemoteEndPoint, FullName);
}
下面是客户端实现:
private ConnectedClient SecureConnection(TcpClient toSecure)
{
NetworkStream netStr = toSecure.GetStream();
ConnectedClient cc = new ConnectedClient
{
TcpClient = toSecure,
NetStream = netStr
};
byte[] buffer = new byte[128];
int position = 0;
while (position < 127)
{
position += netStr.Read (buffer, position, 128 - position);
}
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters
{
Exponent = new byte[] {1, 0, 1},
Modulus = buffer
};
RSA.ImportParameters(RSAKeyInfo);
Rijndael rjindael = new RijndaelManaged();
rjindael.GenerateKey();
rjindael.GenerateIV();
byte[] keyToSend = RSA.Encrypt(rjindael.Key, true);
byte[] IvToSend = RSA.Encrypt(rjindael.IV, true);
netStr.Write(keyToSend, 0, 128);
netStr.Flush();
netStr.Write(IvToSend, 0, 128);
netStr.Flush();
cc.Encrypt = rjindael.CreateEncryptor();
cc.Decrypt = rjindael.CreateDecryptor();
cc.Rijndael = rjindael;
Debug.WriteLine("[TCP] ConnectedClient -> Connection to " + toSecure.Client.RemoteEndPoint + " secured successfully");
cc.WriteOnStream(SharedGlobals.FullUsername);
return cc;
}
问题出在客户端:byte[] realKey = RSA.Decrypt(keyReceived, true);
用OAEP decoding error
掷出CryptographicException
这个异常只在Mono中抛出,而不是标准的。net
这个问题是因为。net和Mono之间的指数不一样。net总是生成一个byte[]{1,0,1}
(至少从我看到的)。现在我用公钥发送指数,它运行正常