Installing a certificate in a .MSI Custom Action doesn't work properly

旧巷老猫 提交于 2019-11-30 09:41:05

Well, at least this question earned me a tumble weed badge...

It turned out to be the permissions on the installed key file. I had to grant all users read permissions.

And here is the code I used to grant all (local) users read permissions:

private static void AddAccessToCertificate(X509Certificate2 cert)
{
  RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;
  if (rsa == null) return;

  string keyfilepath = FindKeyLocation(rsa.CspKeyContainerInfo.UniqueKeyContainerName);

  FileInfo file = new FileInfo(System.IO.Path.Combine(keyfilepath, rsa.CspKeyContainerInfo.UniqueKeyContainerName));

  FileSecurity fs = file.GetAccessControl();

  SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
  fs.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.Read, AccessControlType.Allow));
  file.SetAccessControl(fs);
}

private static string FindKeyLocation(string keyFileName)
{
  string pathCommAppData = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Microsoft\Crypto\RSA\MachineKeys");
  string[] textArray = Directory.GetFiles(pathCommAppData, keyFileName);
  if (textArray.Length > 0) return pathCommAppData;

  string pathAppData = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Crypto\RSA\");
  textArray = Directory.GetDirectories(pathAppData);
  if (textArray.Length > 0)
  {
    foreach (string str in textArray)
    {
      textArray = Directory.GetFiles(str, keyFileName);
      if (textArray.Length != 0) return str;
    }
  }
  return "Private key exists but is not accessible";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!