c# - > Kafka over TLS:"收到的消息是意外的或格式错误的"

时间:2016-08-09 14:29:59

标签: c# ssl tls1.2

我尝试连接到Kafka,从C#客户端启用TLS并获取异常" 收到的消息是意外的或格式错误的"在致电sslStream.AuthenticateAsClient()期间。不幸的是,到目前为止,互联网上的帖子都没有帮我解决问题。知道什么可能是错的吗?

以下是我用于启动连接的最小样本C#代码

namespace test_tls {
    class Program {
        static string clientCertificateFile = "C:\\Temp\\<CLIENT_CERTIFICATE_FILE>.crt";
        static X509Certificate2 clientCertificate = new X509Certificate2(clientCertificateFile);

        static void Main(string[] args) {
            var clientCertificateCollection = new X509Certificate2Collection(new X509Certificate2[] { clientCertificate });

            try {
                using( var client = new TcpClient("<IP_ADDRESS>", 9093) )
                using( var sslStream = new SslStream(client.GetStream(), false, CertificateValidator) ) {

                    sslStream.AuthenticateAsClient("<TARGET_HOST_NAME_AS_IN_THE_CERTIFICATE>",
                        clientCertificateCollection, SslProtocols.Tls, false);

                    //send/receive from the sslStream
                }
            }
            catch( Exception e ) {
                Console.Out.WriteLine(e);
                Console.Out.WriteLine("\n\n\nPress ENTER to exit");
                Console.In.ReadLine();
            }
        }

        static bool CertificateValidator(Object sender, 
                X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
            if( sslPolicyErrors == SslPolicyErrors.None ) {
                return true;
            }
            if( sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors ) {
                //we don't have a proper certificate tree
                return true;
            } 
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在进行一些挖掘之后,似乎错误消息绝对具有误导性,问题的根本原因是 - 在连接过程中缺少“客户端证书的私钥”。

X509Certificate2应该使用这种方式加载

string clientCertificateFile = "C:\\path\\to\\my.certificate.pfx";
X509Certificate2 clientCertificate = new X509Certificate2(clientCertificateFile, "<password>");

或从本地证书存储区(应该使用私钥导入它)

X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2 cert = store.Certificates.Find(X509FindType.FindBySubjectName, "<Certificate 'Issued To' name>", false)[0];

注意:如果您在单独的文件中拥有证书和私钥,则可以使用此命令将它们合并到PFX文件中

openssl pkcs12 -export -in my.cer -inkey my.key -out mycert.pfx