in src/PFXImportPowershell/EncryptionUtilities/Source/ManagedRSAEncryption.cs [270:345]
public bool ImportKeyToKSP(string providerName, string keyName, string filePath, 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;
byte[] keyBlob = File.ReadAllBytes(filePath);
CngProperty keyBlobProp = new CngProperty(new CngKeyBlobFormat("RSAFULLPRIVATEBLOB").Format, keyBlob, CngPropertyOptions.None);
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 = { permissions, keyBlobProp },
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 = { keyBlobProp },
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;
}
}
}