Dre*_*TaX 6 c# ssl x509certificate2
我正在使用这个小类,它返回一个字节数组中的 pfx 文件。
服务器端:
byte[] serverCertificatebyte;
var date = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
serverCertificatebyte = Certificate.CreateSelfSignCertificatePfx("CN=RustBuster" + RandomString(5),
date,
date.AddDays(7));
Run Code Online (Sandbox Code Playgroud)
然后我将其发送给客户端(长度:1654):
tcpClient.GetStream().Write(serverCertificatebyte , 0, serverCertificatebyte .Length);
Run Code Online (Sandbox Code Playgroud)
一旦客户端读取它,我想将它转换为证书类:(这里长度也是1654)
我尝试做一个新的 X509Certificate2(data); 我在下面得到了错误。这适用于服务器端。怎么了?
我还尝试了 new X509Certificate2(data, string.Empty); 并得到同样的错误
错误 System.Security.Cryptography.CryptographicException:无法解码证书。---> System.Security.Cryptography.CryptographicException:输入数据无法编码为有效证书。---> System.ArgumentOutOfRangeException:不能为负数。
参数名称:长度
在 System.String.Substring (Int32 startIndex, Int32 length) [0x00000] in :0
在 Mono.Security.X509.X509Certificate.PEM (System.String 类型,System.Byte[] 数据)[0x00000] 中:0
在 Mono.Security.X509.X509Certificate..ctor (System.Byte[] data) [0x00000] 中:0
漫长的思考和帮助请求终于让我找到了解决方案。
以下方法或示例对我所拥有的持久连接根本不起作用。
在服务器端,您首先必须获取要发送的字节的长度,并将其写入流中。这很可能是长度为 4 的字节。
byte[] intBytes = BitConverter.GetBytes(serverCertificatebyte.Length);
Array.Reverse(intBytes);
Run Code Online (Sandbox Code Playgroud)
在客户端,读取该字节,并将其转换为 int:
byte[] length = new byte[4];
int red = 0;
while (true)
{
red = stream.Read(length, 0, length.Length);
if (red != 0)
{
break;
}
}
if (BitConverter.IsLittleEndian)
{
Array.Reverse(length);
}
int i = (BitConverter.ToInt32(length, 0)); // The length of the byte that the server sent
// By this time your server already sent the byte (Right after you sent the length) tcpClient.GetStream().Write(byte, 0, byte.Length);
byte[] data = ByteReader(i);
Run Code Online (Sandbox Code Playgroud)
此方法将读取您从服务器发送的字节,直到可能
internal byte[] ByteReader(int length)
{
using (NetworkStream stream = client.GetStream())
{
byte[] data = new byte[length];
using (MemoryStream ms = new MemoryStream())
{
int numBytesRead;
int numBytesReadsofar = 0;
while (true)
{
numBytesRead = stream.Read(data, 0, data.Length);
numBytesReadsofar += numBytesRead;
ms.Write(data, 0, numBytesRead);
if (numBytesReadsofar == length)
{
break;
}
}
return ms.ToArray();
}
}
}
Run Code Online (Sandbox Code Playgroud)
与微软文档页面上提供的其他示例不同,该解决方案似乎运行得很好。我希望这对其他人也有帮助。
| 归档时间: |
|
| 查看次数: |
5132 次 |
| 最近记录: |