如何在 C# 中使用.key文件

本文关键字:key 文件 | 更新日期: 2023-09-27 18:32:49

我正在设置 AS2 通信以对客户的文件进行签名。 据我了解,签名是通过AS2通信工作的,我们将使用私钥对我们发送的数据进行签名,他们将使用我们的公钥进行验证。

我的问题:我的 IT 部门给了我一个.cer和一个.key文件。 .cer文件中没有私钥,显然.key文件是私钥。 客户会将.cer文件添加到其受信任的根目录,以验证我们的消息。 我在理解如何使用.key文件对数据进行签名时遇到问题。 这不是我可以添加到个人证书存储的内容,因此我不能简单地获取证书并执行以下操作:

//Open my Personal cert store.
X509Store my = new X509Store(StoreName.My, StoreLocation.LocalMachine);
my.Open(OpenFlags.ReadOnly);
RSACryptoServiceProvider csp = null;
foreach (X509Certificate2 cert in my.Certificates)
{
    if (cert.Subject.Contains("My certificate subject"))
    {
        // We found it. 
        // Get its associated CSP and private key
        csp = (RSACryptoServiceProvider)cert.PrivateKey;
    }
}
// Hash the data
SHA256Managed sha256 = new SHA256Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] hash = sha256.ComputeHash(arMessage);
// Sign the hash
return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256"));

由于.key文件不能存储在证书存储中,如何直接使用 .key 文件获取作为 RSACryptoServiceProvider 的私钥?

如何在 C# 中使用.key文件

我只知道如何继续使用 PFX 文件,但将您的 KEY 文件转换为 PFX 应该不是问题。请参阅此帖子:

是否可以将 SSL 证书从.key文件转换为 .pfx?

稍后,您可以使用此方法手动打开证书文件:

// This you should know
var certPath = @"path-to-file.pfx";
var certPass = @"password-goes-here";
// Create a collection object and populate it using the PFX file
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import(certPath, certPass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
//Then you can iterate over the collection:
foreach (X509Certificate2 cert in collection)
{
     // Bingo
     // Here you can do whatever you want with "cert"
}

我以稍微不同的方式做了类似的事情。如果这根本没有帮助,请原谅我,我可以删除它。

我在这里没有做任何签名,但你也许可以从中弄清楚如何。

var collection = new X509Certificate2Collection();
collection.Import(System.Web.Hosting.HostingEnvironment.MapPath(pathToPrivateKey), privateKeyPassword, X509KeyStorageFlags.MachineKeySet);
var requestToPing = (HttpWebRequest)WebRequest.Create(dropOffURL);
requestToPing.Method = "POST";
requestToPing.PreAuthenticate = true;
requestToPing.ClientCertificates.Add(collection[0]);