简体   繁体   English

SSL TCP SslStream 服务器抛出未处理的异常“System.Security.Cryptography.CryptographicException:找不到原始签名者”

[英]SSL TCP SslStream Server throws unhandled exception “System.Security.Cryptography.CryptographicException: cannot find the original signer”

I'm trying to create a C# TCP server to receive TCP data with SslStream on a Windows 2008 server from a client (objective C mobile application) sending TCP data.我正在尝试创建一个 C# TCP 服务器,以便在 Windows 2008 服务器上使用SslStream从发送 TCP 数据的客户端(目标 C 移动应用程序)接收 TCP 数据。

I'm using Microsoft's sample code ( NOTE: my modified version of that code is at the end of this question) ie it is the server code, just under the line " The following code example demonstrates creating an TcpListener that uses the SslStream class to communicate with clients. ")我正在使用 Microsoft 的示例代码注意:该代码的修改版本在此问题的末尾)即它是服务器代码,就在“下面的代码示例中”演示了创建一个使用 SslStream 类的 TcpListener与客户沟通。 ”)

Exception例外

However, when I run this server code I get the following exception:但是,当我运行此服务器代码时,出现以下异常:

System.Security.Cryptography.CryptographicException: Cannot find the original si
gner.

   at System.Security.Cryptography.CryptographicException.ThrowCryptographicExce
ption(Int32 hr)
   at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(
String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCer
tContextHandle& pCertCtx)
   at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertific
ateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlag
s)
   at System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCe
rtFile(String filename)
   at SslTcpServer.LocationSslTcpServer.RunServer(String certificate) in c:\SslTcpServer\Program.cs:line 20
   at SslTcpServer.Program.Main(String[] args) in c:\SslTcpServer\Program.cs:line 180

I've also tried the code at http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate.aspx and it throws a similar exception.我还尝试了http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate.aspx 上的代码,它抛出了类似的异常。

Additional Information附加信息

I got my SSL certificate from NameCheap.我从 NameCheap 获得了我的 SSL 证书。 I purchased the EssentialSSL Wildcard certificate.我购买了EssentialSSL 通配符证书。 I made a Created Certificate Request on the Windows 2008 server ie that gaint text starting with:我在 Windows 2008 服务器上创建了一个创建的证书请求,即以以下内容开头的文本:

    -----BEGIN NEW CERTIFICATE REQUEST-----
            alots of random characters
    -----END NEW CERTIFICATE REQUEST-----

and uploaded that gaint text file to NameCheap and got emailed a Certificate.cer file.并将该文本文件上传到 NameCheap 并通过电子邮件发送了Certificate.cer文件。

My Code我的代码

public sealed class LocationSslTcpServer
{
    static X509Certificate serverCertificate = null;
    // The certificate parameter specifies the name of the file 
    // containing the machine certificate.
    public static void RunServer(string certificate)
    {
        serverCertificate = X509Certificate.CreateFromCertFile(certificate);
        // Create a TCP/IP (IPv4) socket and listen for incoming connections.
        TcpListener listener = new TcpListener(IPAddress.Any, 8080);
        listener.Start();
        while (true)
        {
            Console.WriteLine("Waiting for a client to connect...");
            // Application blocks while waiting for an incoming connection.
            // Type CNTL-C to terminate the server.
            TcpClient client = listener.AcceptTcpClient();
            ProcessClient(client);
        }
    }
    static void ProcessClient(TcpClient client)
    {
        // A client has connected. Create the 
        // SslStream using the client's network stream.
        SslStream sslStream = new SslStream(
            client.GetStream(), false);
        // Authenticate the server but don't require the client to authenticate.
        try
        {
            sslStream.AuthenticateAsServer(serverCertificate,
                false, SslProtocols.Tls, true);
            // Display the properties and settings for the authenticated stream.
            DisplaySecurityLevel(sslStream);
            DisplaySecurityServices(sslStream);
            DisplayCertificateInformation(sslStream);
            DisplayStreamProperties(sslStream);

            // Set timeouts for the read and write to 5 seconds.
            sslStream.ReadTimeout = 5000;
            sslStream.WriteTimeout = 5000;
            // Read a message from the client.   
            Console.WriteLine("Waiting for client message...");
            string messageData = ReadMessage(sslStream);
            Console.WriteLine("Received: {0}", messageData);

            // Write a message to the client.
            byte[] message = Encoding.UTF8.GetBytes("Hello from the server.<EOF>");
            Console.WriteLine("Sending hello message.");
            sslStream.Write(message);
        }
        catch (AuthenticationException e)
        {
            Console.WriteLine("Exception: {0}", e.Message);
            if (e.InnerException != null)
            {
                Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
            }
            Console.WriteLine("Authentication failed - closing the connection.");
            sslStream.Close();
            client.Close();
            return;
        }
        finally
        {
            // The client stream will be closed with the sslStream
            // because we specified this behavior when creating
            // the sslStream.
            sslStream.Close();
            client.Close();
        }
    }
    static string ReadMessage(SslStream sslStream)
    {
        // Read the  message sent by the client.
        // The client signals the end of the message using the
        // "<EOF>" marker.
        byte[] buffer = new byte[2048];
        StringBuilder messageData = new StringBuilder();
        int bytes = -1;
        do
        {
            // Read the client's test message.
            bytes = sslStream.Read(buffer, 0, buffer.Length);

            // Use Decoder class to convert from bytes to UTF8
            // in case a character spans two buffers.
            Decoder decoder = Encoding.UTF8.GetDecoder();
            char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
            decoder.GetChars(buffer, 0, bytes, chars, 0);
            messageData.Append(chars);
            // Check for EOF or an empty message.
            if (messageData.ToString().IndexOf("<EOF>") != -1)
            {
                break;
            }
        } while (bytes != 0);

        return messageData.ToString();
    }
    static void DisplaySecurityLevel(SslStream stream)
    {
        Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
        Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
        Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
        Console.WriteLine("Protocol: {0}", stream.SslProtocol);
    }
    static void DisplaySecurityServices(SslStream stream)
    {
        Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
        Console.WriteLine("IsSigned: {0}", stream.IsSigned);
        Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
    }
    static void DisplayStreamProperties(SslStream stream)
    {
        Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
        Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
    }
    static void DisplayCertificateInformation(SslStream stream)
    {
        Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);

        X509Certificate localCertificate = stream.LocalCertificate;
        if (stream.LocalCertificate != null)
        {
            Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
                localCertificate.Subject,
                localCertificate.GetEffectiveDateString(),
                localCertificate.GetExpirationDateString());
        }
        else
        {
            Console.WriteLine("Local certificate is null.");
        }
        // Display the properties of the client's certificate.
        X509Certificate remoteCertificate = stream.RemoteCertificate;
        if (stream.RemoteCertificate != null)
        {
            Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
                remoteCertificate.Subject,
                remoteCertificate.GetEffectiveDateString(),
                remoteCertificate.GetExpirationDateString());
        }
        else
        {
            Console.WriteLine("Remote certificate is null.");
        }
    }
    public static void DisplayUsage()
    {
        Console.WriteLine("To start the server specify:");
        Console.WriteLine("serverSync certificateFile.cer");
        Environment.Exit(1);
    }
}

class Program
{
    static int Main(string[] args)
    {
        string certificate = null;
  
        certificate = "Certificate.cer";
        try
        {
            LocationSslTcpServer.RunServer(certificate);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
            Console.ReadLine();
        }
        return 0;

        
    }
}

Thanks in advance for helping!提前感谢您的帮助!

I successfully used X.509 Digital Certificate Generator to:我成功地使用X.509 数字证书生成器来:

  1. Create CA certificate (Ca.pfx).创建CA 证书(Ca.pfx)。
  2. Create Client certificate signed with a CA certificate (Client.pfx).创建使用 CA 证书 (Client.pfx) 签名的客户端证书
  3. Create Server certificate signed with a CA certificate (Server.pfx).创建使用 CA 证书 (Server.pfx) 签名的服务器证书
  4. Install CA certificate (Ca.pfx) in the Trusted Root Certificate folder .Trusted Root Certificate 文件夹中安装CA 证书(Ca.pfx)。
  5. Install Client and Server certificate (Client.pfx and Server.pfx) in Personal folder .Personal 文件夹中安装客户端和服务器证书(Client.pfx 和 Server.pfx)。

For steps 4 and 5: From the Search Box (near the Windows start button - left bottom your desktop) typo: cert , then select the Manage Computer Certificates application.对于第 4 步和第 5 步:从搜索框(Windows 开始按钮附近 - 桌面左下角)输入: cert ,然后选择“管理计算机证书”应用程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 System.Security.Cryptography.CryptographicException:系统找不到指定的文件 - System.Security.Cryptography.CryptographicException: The system cannot find the file specified 未处理的异常。 System.Security.Cryptography.CryptographicException:在密钥环中找不到密钥 {....} - Unhandled exception. System.Security.Cryptography.CryptographicException: The key {....} was not found in the key ring PrivateKey抛出了System.Security.Cryptography.CryptographicException类型的异常 - PrivateKey threw an exception of type System.Security.Cryptography.CryptographicException “System.Security.Cryptography.CryptographicException”类型的异常:密钥集不存在 - An exception of type 'System.Security.Cryptography.CryptographicException': keyset does not exist AppHarbor-System.Security.Cryptography.CryptographicException:系统找不到指定的文件 - AppHarbor - System.Security.Cryptography.CryptographicException: The system cannot find the file specified CngKey System.Security.Cryptography.CryptographicException 系统找不到 Azure 上指定的文件 - CngKey System.Security.Cryptography.CryptographicException The system cannot find the file specified on Azure TwilioRequestValidator 中的瞬态 System.Security.Cryptography.CryptographicException - Transient System.Security.Cryptography.CryptographicException in TwilioRequestValidator System.Security.Cryptography.CryptographicException:句柄无效 - System.Security.Cryptography.CryptographicException: The handle is invalid System.Security.Cryptography.CryptographicException:参数不正确 - System.Security.Cryptography.CryptographicException: The parameter is incorrect System.Security.Cryptography.CryptographicException:'Cryptography_OAEPDecoding' - System.Security.Cryptography.CryptographicException: 'Cryptography_OAEPDecoding'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM