【问题标题】:Load certificate keys into CngKey class for use with DiffieHellman (ECDiffieHellmanCng class)将证书密钥加载到 CngKey 类中以用于 DiffieHellman(ECDiffieHellmanCng 类)
【发布时间】:2013-07-29 16:23:12
【问题描述】:

这与 .NET / C# 有关。假设在 PFX 或 PKCS#12 文件中有证书 + 私钥(P521 ECC 之一)。我们已通过安装此证书及其私钥将其加载到 Windows 证书存储中(双击 PFX 或运行 certutil -f -p myPfxPassword -importPFX MY SomeEcCert.pfx)。我注意到如果证书兼容(例如 p521 曲线),它会自动安装为 CNG 证书/密钥。

现在,如何将私钥加载到 CngKey 中,以便在 ECDiffieHellmanCng 类中使用它?我还想加载 X509 (CNG) 证书以读取它的序列号、发行者、通用名称等以进行一些簿记。

var myCngKey = SomehowLoadTheCngKey("my ecc certificate"); // <== ??
var myDH = new ECDiffieHellmanCng(myCngKey);

【问题讨论】:

    标签: c# encryption public-key-encryption diffie-hellman cng


    【解决方案1】:

    嗯,.NET 没有很好的 CNG API。如果你甚至从他们的 API 表面看,你会立即发现这有点荒谬,尤其是考虑到两者都来自微软,而 CNG 是整个 Windows 平台上所有 Crypto API 中最严重的。

    因此您需要使用CLRSecurity,它为 C++ CNG API 提供 C# 接口(通过 P/Invoke)。即使这样,它也不是最好的 API 设计。但它有帮助。

    // Load the cert, many ways, one implementation
    var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
    var certs = store.Certificates.Find(X509FindType.FindBySubjectName, "My cert subject name", true);
    store.Close();
    
    if (certs.Count > 0)
        cert = certs[0];
    else
        return;
    
    // Magic happens here! We load the private CngKey (if it exists)
    // You need CLR Security for this, it manages the P/Invoke
    // into the C++ api behind the scenes. 
    var pvtCngKey = cert.GetCngPrivateKey(); 
    
    // Create the DiffieHellman helper
    var ecDh = new ECDiffieHellmanCng(ourPvtEcCngKey)
    {
       KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash,
       HashAlgorithm = CngAlgorithm.Sha256
    };
    
    ECDiffieHellmanCngPublicKey theirPubCngKey = LoadOtherPartiesCngPublicKey(theirCert);
    byte[] symKey = ecDh.DeriveKeyMaterial(theirPubCngKey);
    

    【讨论】:

    • LoadOtherPartiesCngPublicKey(theirCert)的实现是什么样的?
    • 请注意,“CLRSecurity”可通过 NuGet for .NET Framework 获得:Security.Cryptography
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2020-10-23
    • 2013-04-10
    相关资源
    最近更新 更多