如何使用RSACng将公钥和私钥对保留在密钥存储提供程序中?

时间:2019-05-15 09:05:29

标签: cryptography public-key-encryption pki rsacryptoserviceprovider cng

我有一个由RSACng类生成的公钥和私钥对。我可以将私钥持久保存到本地计算机->(程序数据->加密-> RSA->密钥)下的我的KSP(MicrosoftSoftwareKeyStorageProvider)中。但是,我无法持久保存由RSACng生成的公钥。如何将RSACng中的公钥持久保存到KSP(MicrosoftSoftwareKeyStorageProvider)?

我已经尝试使用CngKey保留公共密钥,但是这使我“不支持该操作”。请在下面的代码中查找。

public static void SaveKeyPairToKSP(KeyGenerationResult keyData, string keyName)
{
    var myKSP = CngProvider.MicrosoftSoftwareKeyStorageProvider;
    const bool MachineKey = true;

    if (!CngKey.Exists(keyName, myKSP))
    {
        var keyParams = new CngKeyCreationParameters
        {
            ExportPolicy = CngExportPolicies.AllowArchiving,
            KeyCreationOptions = (MachineKey) ? CngKeyCreationOptions.MachineKey : CngKeyCreationOptions.None,
            Provider = myKSP
        };
        keyParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(keyData.KeySize), CngPropertyOptions.None));
        keyParams.Parameters.Add(new CngProperty(CngKeyBlobFormat.GenericPrivateBlob.Format, keyData.PrivateBytes, CngPropertyOptions.Persist));
        //Here is my public key that i want to store in my KSP
        keyParams.Parameters.Add(new CngProperty(CngKeyBlobFormat.GenericPublicBlob.Format, keyData.PublicBytes, CngPropertyOptions.Persist));
        CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams);
    }
}

0 个答案:

没有答案