1

为了避免注册表重定向到 Wow64 键,如何翻译以下使用Microsoft.Win32API的代码

public void SetKeyAccessControl(
            RegistryKey rootKey, string subKeyName, string identity, 
            RegistryRights rights, InheritanceFlags inheritanceFlags,
            PropagationFlags propagationFlags, AccessControlType accessType)
{
   using (RegistryKey regKey = rootKey.OpenSubKey(subKeyName, true))
   {
       RegistrySecurity acl = new RegistrySecurity();
       RegistryAccessRule rule = new RegistryAccessRule(identity, rights, inheritanceFlags, propagationFlags, accessType);
       acl.AddAccessRule(rule);

       regKey.SetAccessControl(acl);
   }            
}

使用 advapi32 RegSetKeySecurity API

[DllImport(@"advapi32.dll", EntryPoint = "RegSetKeySecurity", SetLastError = true)]
internal static extern int RegSetKeySecurity(IntPtr handle, uint securityInformation, IntPtr pSecurityDescriptor);
4

2 回答 2

3

为避免注册表重定向,您可以执行以下操作...

SafeRegistryHandle handle = rootKey.Handle;

RegistryKey rootKey32 = RegistryKey.FromHandle(handle, RegistryView.Registry32);

RegistryKey rootKey64 = RegistryKey.FromHandle(handle, RegistryView.Registry64);

然后,您可以使用 rootKey32 或 rootKey64 打开子键,您将获得所请求视图的子键。

至少它适用于我尝试过的少数测试用例。而且,根据FromHandle的文档...

该方法的view参数用于后续操作,例如打开子键

于 2011-07-28T04:12:22.733 回答
0

需要涉及另一种本机方法并给定 SDDL,以下代码在正确的注册表项上设置 ACL:


[DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string stringSecurityDescriptor, int stringSDRevision, out IntPtr ppSecurityDescriptor, ref int securityDescriptorSize);

string sddl = "...";
IntPtr secDescriptor = IntPtr.Zero;
int size = 0;
ConvertStringSecurityDescriptorToSecurityDescriptor
   (
      sddl,
      1,                              // revision 1
      out secDescriptor,
      ref size
   );

// get handle with RegOpenKeyEx

RegSetKeySecurity
(
     handle,
     0x00000004,                      // DACL_SECURITY_INFORMATION
     secDescriptor
);
于 2011-09-07T22:22:00.973 回答