Creating RSA CNG key in .NET

Cryptography

Here is an example of creating a new RSA key or checking if there is an existing one, then opening it.


CngProvider tpmProvider = new CngProvider("Microsoft Platform Crypto Provider");
            
CngKey cngKey;

bool keyExists = CngKey.Exists("keyname", tpmProvider, CngKeyOpenOptions.MachineKey);
            
if (!keyExists)
{
                
    CngKeyCreationParameters cngKeyCreationParameters = new CngKeyCreationParameters()
    {
	    KeyCreationOptions = CngKeyCreationOptions.MachineKey,
        KeyUsage = CngKeyUsages.AllUsages,
        ExportPolicy = CngExportPolicies.None,
        Provider = tpmProvider,
    };

    CngProperty keySizeProperty = new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None);
    cngKeyCreationParameters.Parameters.Add(keySizeProperty);

    cngKey = CngKey.Create(CngAlgorithm.Rsa, "keyname", cngKeyCreationParameters);
}
else
{
    cngKey = CngKey.Open("keyname", tpmProvider, CngKeyOpenOptions.MachineKey);
}

RSACng rsaKey = new RSACng(cngKey);

Other CngProperty values can be as described here: https://referencesource.microsoft.com/#system.core/System/Security/Cryptography/NCryptNative.cs


internal static class KeyPropertyName {
internal const string Algorithm = "Algorithm Name";                 // NCRYPT_ALGORITHM_PROPERTY
internal const string AlgorithmGroup = "Algorithm Group";           // NCRYPT_ALGORITHM_GROUP_PROPERTY
internal const string ExportPolicy = "Export Policy";               // NCRYPT_EXPORT_POLICY_PROPERTY
internal const string KeyType = "Key Type";                         // NCRYPT_KEY_TYPE_PROPERTY
internal const string KeyUsage = "Key Usage";                       // NCRYPT_KEY_USAGE_PROPERTY
internal const string Length = "Length";                            // NCRYPT_LENGTH_PROPERTY
internal const string Name = "Name";                                // NCRYPT_NAME_PROPERTY
internal const string ParentWindowHandle = "HWND Handle";           // NCRYPT_WINDOW_HANDLE_PROPERTY
internal const string PublicKeyLength = "PublicKeyLength";          // NCRYPT_PUBLIC_KEY_LENGTH (Win10+)
internal const string ProviderHandle = "Provider Handle";           // NCRYPT_PROVIDER_HANDLE_PROPERTY
internal const string UIPolicy = "UI Policy";                       // NCRYPT_UI_POLICY_PROPERTY
internal const string UniqueName = "Unique Name";                   // NCRYPT_UNIQUE_NAME_PROPERTY
internal const string UseContext = "Use Context";                   // NCRYPT_USE_CONTEXT_PROPERTY        }

Post a Comment

Previous Post Next Post