質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Visual Studio

Microsoft Visual StudioはMicrosoftによる統合開発環境(IDE)です。多種多様なプログラミング言語に対応しています。

Windows 7

Microsoft Windows 7は過去にリリースされたMicrosoft WindowsのOSであり、Windows8の1代前です。2009年の7月にリリースされ販売されました。Windows7の前はWindowsVistaで、その更に3年前にリリースされました。

Q&A

解決済

1回答

4318閲覧

C#でSSL通信をしたいのですが...

gobou000

総合スコア7

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Visual Studio

Microsoft Visual StudioはMicrosoftによる統合開発環境(IDE)です。多種多様なプログラミング言語に対応しています。

Windows 7

Microsoft Windows 7は過去にリリースされたMicrosoft WindowsのOSであり、Windows8の1代前です。2009年の7月にリリースされ販売されました。Windows7の前はWindowsVistaで、その更に3年前にリリースされました。

0グッド

0クリップ

投稿2018/02/09 13:25

編集2018/02/09 13:43

前提・実現したいこと

C#で暗号化された文をやりとりするサーバーアプリ・クライアントアプリを作成しようと思っています。
まずは以下のURLの最下部の参考プログラムをほぼそのまま走らせてみたのですが、クライアントが接続してくるとエラーになります
https://msdn.microsoft.com/ja-jp/library/system.net.security.sslstream(v=vs.110).aspx

発生している問題・エラーメッセージ

System.NotSupportedException: 'サーバー モード SSL は関連付けられた秘密キーを使用した証明書を使用しなければなりません。'

該当のソースコード

C#

1using System; 2using System.Collections; 3using System.Net; 4using System.Net.Sockets; 5using System.Net.Security; 6using System.Security.Authentication; 7using System.Text; 8using System.Security.Cryptography.X509Certificates; 9using System.IO; 10 11namespace Examples.System.Net 12{ 13 public sealed class SslTcpServer 14 { 15 static X509Certificate serverCertificate = new X509Certificate(@"C:\OpenSSL-Win32\bin\example.com.crt(local.crt)", "testtest"); 16 17 public static int Main(string[] args) 18 { 19 string certificate = @"C:\OpenSSL-Win32\bin\example.com.crt(local.crt)"; 20 if (args == null || args.Length < 1) 21 { 22 //DisplayUsage(); 23 } 24 //certificate = args[0]; 25 SslTcpServer.RunServer(certificate); 26 return 0; 27 } 28 29 public static void RunServer(string certificate) 30 { 31 serverCertificate = X509Certificate.CreateFromCertFile(certificate); 32 // Create a TCP/IP (IPv4) socket and listen for incoming connections. 33 TcpListener listener = new TcpListener(IPAddress.Any, 443); 34 listener.Start(); 35 while (true) 36 { 37 Console.WriteLine("Waiting for a client to connect..."); 38 // Application blocks while waiting for an incoming connection. 39 // Type CNTL-C to terminate the server. 40 TcpClient client = listener.AcceptTcpClient(); 41 ProcessClient(client); 42 } 43 } 44 static void ProcessClient(TcpClient client) 45 { 46 // A client has connected. Create the 47 // SslStream using the client's network stream. 48 SslStream sslStream = new SslStream( 49 client.GetStream(), false); 50 // Authenticate the server but don't require the client to authenticate. 51 try 52 { 53 sslStream.AuthenticateAsServer(serverCertificate, 54 false, SslProtocols.Tls, true); 55 // Display the properties and settings for the authenticated stream. 56 DisplaySecurityLevel(sslStream); 57 DisplaySecurityServices(sslStream); 58 DisplayCertificateInformation(sslStream); 59 DisplayStreamProperties(sslStream); 60 61 // Set timeouts for the read and write to 5 seconds. 62 sslStream.ReadTimeout = 5000; 63 sslStream.WriteTimeout = 5000; 64 // Read a message from the client. 65 Console.WriteLine("Waiting for client message..."); 66 string messageData = ReadMessage(sslStream); 67 Console.WriteLine("Received: {0}", messageData); 68 69 // Write a message to the client. 70 byte[] message = Encoding.UTF8.GetBytes("Hello from the server.<EOF>"); 71 Console.WriteLine("Sending hello message."); 72 sslStream.Write(message); 73 } 74 catch (AuthenticationException e) 75 { 76 Console.WriteLine("Exception: {0}", e.Message); 77 if (e.InnerException != null) 78 { 79 Console.WriteLine("Inner exception: {0}", e.InnerException.Message); 80 } 81 Console.WriteLine("Authentication failed - closing the connection."); 82 sslStream.Close(); 83 client.Close(); 84 return; 85 } 86 finally 87 { 88 // The client stream will be closed with the sslStream 89 // because we specified this behavior when creating 90 // the sslStream. 91 sslStream.Close(); 92 client.Close(); 93 } 94 } 95 static string ReadMessage(SslStream sslStream) 96 { 97 // Read the message sent by the client. 98 // The client signals the end of the message using the 99 // "<EOF>" marker. 100 byte[] buffer = new byte[2048]; 101 StringBuilder messageData = new StringBuilder(); 102 int bytes = -1; 103 do 104 { 105 // Read the client's test message. 106 bytes = sslStream.Read(buffer, 0, buffer.Length); 107 108 // Use Decoder class to convert from bytes to UTF8 109 // in case a character spans two buffers. 110 Decoder decoder = Encoding.UTF8.GetDecoder(); 111 char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)]; 112 decoder.GetChars(buffer, 0, bytes, chars, 0); 113 messageData.Append(chars); 114 // Check for EOF or an empty message. 115 if (messageData.ToString().IndexOf("<EOF>") != -1) 116 { 117 break; 118 } 119 } while (bytes != 0); 120 121 return messageData.ToString(); 122 } 123 static void DisplaySecurityLevel(SslStream stream) 124 { 125 Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength); 126 Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength); 127 Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength); 128 Console.WriteLine("Protocol: {0}", stream.SslProtocol); 129 } 130 static void DisplaySecurityServices(SslStream stream) 131 { 132 Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer); 133 Console.WriteLine("IsSigned: {0}", stream.IsSigned); 134 Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted); 135 } 136 static void DisplayStreamProperties(SslStream stream) 137 { 138 Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite); 139 Console.WriteLine("Can timeout: {0}", stream.CanTimeout); 140 } 141 static void DisplayCertificateInformation(SslStream stream) 142 { 143 Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus); 144 145 X509Certificate localCertificate = stream.LocalCertificate; 146 if (stream.LocalCertificate != null) 147 { 148 Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.", 149 localCertificate.Subject, 150 localCertificate.GetEffectiveDateString(), 151 localCertificate.GetExpirationDateString()); 152 } 153 else 154 { 155 Console.WriteLine("Local certificate is null."); 156 } 157 // Display the properties of the client's certificate. 158 X509Certificate remoteCertificate = stream.RemoteCertificate; 159 if (stream.RemoteCertificate != null) 160 { 161 Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.", 162 remoteCertificate.Subject, 163 remoteCertificate.GetEffectiveDateString(), 164 remoteCertificate.GetExpirationDateString()); 165 } 166 else 167 { 168 Console.WriteLine("Remote certificate is null."); 169 } 170 } 171 private static void DisplayUsage() 172 { 173 Console.WriteLine("To start the server specify:"); 174 Console.WriteLine("serverSync certificateFile.cer"); 175 Environment.Exit(1); 176 } 177 178 } 179} 180

補足情報(FW/ツールのバージョンなど)

windows7 visual studio community 2017

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

証明書の作成・インポート・指定しているファイル
どれかが間違っています。pfxやp12がある場合は試してみてください。
インポートしていなければ先にインポートも必要なはずです。
どの様に証明書を作成したか分かれば、手助けできるかもしれません。

また、クライアント側のserverCertificateNameにも注意してください。
証明書のCNと同じ必要があったはずです。

投稿2018/02/13 08:31

sh_akira

総合スコア380

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問