简体   繁体   English

获取“服务器模式 SSL 必须使用具有关联私钥的证书。” X509Certificate2 中的错误由 use.cer 而不是.pfx

[英]Get "The server mode SSL must use a certificate with the associated private key." error in X509Certificate2 by use .cer instead of .pfx

I use.cer and.key files in custom web server for validate ssl with SslStream.AuthenticateAsServerAsync().我在自定义 web 服务器中使用 .cer 和 .key 文件使用 SslStream.AuthenticateAsServerAsync() 验证 ssl。 creating process of X509Certificate2 is some things like this: X509Certificate2 的创建过程是这样的:

var bytes = File.ReadAllBytes(certificatePath);
using var publicKey = new X509Certificate2(bytes,default(string));


var privateKeyText = File.ReadAllText(privateKeyPath);
var privateKeyBlocks = privateKeyText.Split("-", StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim('\n')).ToArray();
var privateKeyBytes = Convert.FromBase64String(privateKeyBlocks[1]);

        
using var rsa = RSA.Create();

if (privateKeyBlocks[0] == "BEGIN PRIVATE KEY")
   {
      rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);
   }
else if (privateKeyBlocks[0] == "BEGIN RSA PRIVATE KEY")
   {
      rsa.ImportRSAPrivateKey(privateKeyBytes, out _);
   }

var keyPair = publicKey.CopyWithPrivateKey(rsa);
return new X509Certificate2(keyPair.Export(X509ContentType.Pfx));

In useing.pfx every this is ok, but by use this code for replace.pfx file (and generating process of it) with.cer and.key files, in SslStream.AuthenticateAsServerAsync() i got this error:在使用.pfx 中,这一切都可以,但是通过在 SslStream.AuthenticateAsServerAsync() 中将此代码用于 replace.pfx 文件(及其生成过程)与 .cer 和 .key 文件,我得到了这个错误:

System.Security.Authentication.AuthenticationException: The server mode SSL must use a certificate with the associated private key.

Other way that i use for do this:我用于执行此操作的其他方式:

 X509Certificate2 certWithKey = default;
 try
 {
   string keyPem = File.ReadAllText(keyFile);
   byte[] keyDer = UnPem(keyPem);
   using (X509Certificate2 certOnly = new X509Certificate2(cerFile))
   {
       using (RSA rsa = RSA.Create())
       {
           // For "BEGIN PRIVATE KEY"
           rsa.ImportPkcs8PrivateKey(keyDer, out _);
           var tmp = certOnly.CopyWithPrivateKey(rsa);
           certWithKey = new X509Certificate2(tmp.Export(X509ContentType.Pfx));
       }
   }
   Serilog.Log.ForContext("Path", cerFile).Information("Create certificate from {FileName} successfully.", Path.GetFileName(cerFile));
 }
 catch (Exception ex)
 {
    Logger.LogError(ex, "Error in create certificate from {Path}", cerFile);
 }
 return certWithKey;
 static byte[] UnPem(string pem)
 {
    // This is a shortcut that assumes valid PEM
    // -----BEGIN words-----\nbase64\n-----END words-----
    const string Dashes = "-----";
    int index0 = pem.IndexOf(Dashes);
    int index1 = pem.IndexOf('\n', index0 + Dashes.Length);
    int index2 = pem.IndexOf(Dashes, index1 + 1);
    return Convert.FromBase64String(pem.Substring(index1, index2 - index1));
}

Also in .net 5 use this new way:同样在.net 5中使用这种新方式:

return X509Certificate2.CreateFromPemFile(certificatePath,privateKeyPath);

But Problem not solved.但是问题没有解决。

All things that i want is create X509Certificate2 from.cer and.key files,not from.pfx file.我想要的所有东西都是从.cer 和 .key 文件创建 X509Certificate2,而不是从.pfx 文件。 I don't know that and where is problem.create X509Certificate2 cause problem or i miss some thins else(for example in validate sslstream).我不知道问题在哪里以及问题在哪里。创建 X509Certificate2 导致问题,或者我错过了其他一些东西(例如在验证 sslstream 中)。 tanks for help me to know problem and best way for doing this.坦克帮助我了解问题和最好的方法。

By tanks of bartonjs , my problem solved with this:通过bartonjs的坦克,我的问题解决了:

string pass = Guid.NewGuid().ToString();
var certificate = X509Certificate2.CreateFromPemFile(certificatePath, privateKeyPath);
return new X509Certificate2(certificate.Export(X509ContentType.Pfx, pass), pass);

Create in-memory.pfx type certificate from.cer file with random password and use it instead of original certificate.使用随机密码从.cer 文件创建 in-memory.pfx 类型的证书,并使用它代替原始证书。

暂无
暂无

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

相关问题 服务器模式 SSL 必须使用具有关联私钥的证书 - 在 TLS 握手期间 - The server mode SSL must use a certificate with the associated private key - during TLS handshake SslStream.AuthenticateAsServer 抛出服务器模式 SSL 必须使用具有关联私钥的证书 - SslStream.AuthenticateAsServer throws The server mode SSL must use a certificate with the associated private key SslStream.AuthenticateAsServer异常-服务器模式SSL必须使用带有关联私钥的证书 - SslStream.AuthenticateAsServer exception - The server mode SSL must use a certificate with the associated private key X509Certificate2 的 .pem 私钥 - .pem private key to X509Certificate2 为什么自签名 PFX X509Certificate2 私钥会引发 NotSupportedException? - Why does self signed PFX X509Certificate2 private key raise a NotSupportedException? 使用 X509Certificate2 提示输入密码以使用私钥执行数字签名 - Performing a digital signature using X509Certificate2 prompt for a password to use private key 将X509Certificate2证书与.NET中的私钥相关联 - Associating an X509Certificate2 certificate with a private key in .NET RSAParameters到pfx(X509Certificate2)转换 - RSAParameters to pfx (X509Certificate2) conversion C# SSL 服务器模式必须使用带有相应私钥的证书 - C# SSL server mode must use a certificate with the corresponding private key X509Certificate2-如果使用ECC证书,则访问被拒绝异常 - X509Certificate2 - Access Denied Exception if use ECC certificate
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM