gpt4 book ai didi

c# -> Kafka 通过 TLS : "The message received was unexpected or badly formatted"

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:24 27 4
gpt4 key购买 nike

我正在尝试连接到从 C# 客户端启用 TLS 的 Kafka,并在调用 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;
}
}
}

最佳答案

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

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

关于c# -> Kafka 通过 TLS : "The message received was unexpected or badly formatted",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38853588/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com