in src/PFXImportPowershell/EncryptionUtilities/Source/ManagedRSAEncryption.cs [135:207]
public bool TryGenerateLocalRSAKey(string providerName, string keyName, int keyLength = 2048, bool makeExportable = false)
{
CngProvider provider = new CngProvider(providerName);
bool keyExists = doesKeyExists(provider, keyName);
if (keyExists)
{
//Key already exists. Can't create it.
return false;
}
CryptoKeySecurity sec = new CryptoKeySecurity();
CngKeyCreationParameters keyParams = null;
if (IsMicrosoftSoftwareKSP(provider))
{
sec.AddAccessRule(
new CryptoKeyAccessRule(
new SecurityIdentifier(sidType: WellKnownSidType.BuiltinAdministratorsSid, domainSid: null),
cryptoKeyRights: CryptoKeyRights.FullControl,
type: AccessControlType.Allow));
sec.AddAccessRule(
new CryptoKeyAccessRule(
new SecurityIdentifier(sidType: WellKnownSidType.BuiltinSystemOperatorsSid, domainSid: null),
cryptoKeyRights: CryptoKeyRights.GenericRead,
type: AccessControlType.Allow));
const string NCRYPT_SECURITY_DESCR_PROPERTY = "Security Descr";
const CngPropertyOptions DACL_SECURITY_INFORMATION = (CngPropertyOptions)4;
CngProperty permissions = new CngProperty(
NCRYPT_SECURITY_DESCR_PROPERTY,
sec.GetSecurityDescriptorBinaryForm(),
CngPropertyOptions.Persist | DACL_SECURITY_INFORMATION);
keyParams = new CngKeyCreationParameters()
{
ExportPolicy = makeExportable ? CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport : CngExportPolicies.None,
Provider = provider,
Parameters = { new CngProperty("Length", BitConverter.GetBytes(keyLength), CngPropertyOptions.None),
permissions},
KeyCreationOptions = CngKeyCreationOptions.MachineKey
};
using (CngKey key = CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams))
{
if (key == null)
{
return false;
}
return true;
}
}
else
{
keyParams = new CngKeyCreationParameters()
{
ExportPolicy = makeExportable ? CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport : CngExportPolicies.None,
Provider = provider,
Parameters = { new CngProperty("Length", BitConverter.GetBytes(keyLength), CngPropertyOptions.None) },
KeyCreationOptions = CngKeyCreationOptions.MachineKey
};
using (CngKey key = CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams))
{
if (key == null)
{
return false;
}
// nothing to do inside here, except to return without throwing an exception
return true;
}
}
}