//private static readonly byte[] _genericIv = ConvertEx.FromBase16String("C9DCF37AED8574A1441FD82DB743765C");

        public static WindowsImpersonationContext ImpersonateWindowsUser(string userName, string domain, string password)
        {
            var token          = IntPtr.Zero;
            var tokenDuplicate = IntPtr.Zero;

            try
            {
                if (CoreExtensions.RevertToSelf())
                {
                    if (CoreExtensions.LogonUserA(userName, domain, password, CoreExtensions.LOGON32_LOGON_INTERACTIVE, CoreExtensions.LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        if (CoreExtensions.DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            var tempWindowsIdentity  = new WindowsIdentity(tokenDuplicate);
                            var impersonationContext = tempWindowsIdentity.Impersonate();
                            if (impersonationContext != null)
                            {
                                CoreExtensions.CloseHandle(token);
                                CoreExtensions.CloseHandle(tokenDuplicate);
                                return(impersonationContext);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    CoreExtensions.CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CoreExtensions.CloseHandle(tokenDuplicate);
                }
            }
            throw new Exception("Unable to login.");
        }