2010-03-23 52 views
1

下面的代碼不起作用:ProtectedData.Unprotect()後模擬()

IntPtr token = Win32Dll.LogonUser(「user1」, 「mydomain」, 「password1」); 
WindowsIdentity id = new WindowsIdentity(token); 
WindowsImpersonationContext ic = id.Impersonate(); 
byte[] unprotectedBytes = ProtectedData.Unprotect(passwordBytes, null, DataProtectionScope.CurrentUser); 
password = Encoding.Unicode.GetString(unprotectedBytes); 
ic.Undo(); 

密碼不解密。

MSDN說

"If you use this method during impersonation, you may receive the following error: "Key not valid for use in specified state." This error can be prevented by loading the profile of the user you want to impersonate, before calling the method."

回答

0

沒有嘗試這樣做我自己,但你可以嘗試使用LoadUserProfile非託管API調用。欲瞭解更多信息,請查詢here

有一些related SO questions

+0

謝謝您的答覆啓用PRIVS。 但我試圖在「... id.Impersonate();」之後調用LoadUserProfile()和代碼仍然沒有工作。 此外,我不知道如何處理函數LoadUserProfile()(其返回IntPtr的令牌)的結果做。 我只是調用LoadUserProfile()嗎? 我是否會用令牌做點什麼? – Andrey 2010-03-23 20:24:50

+0

恐怕我不知道如何處理LoadUserProfile的結果。我試圖重現你的問題,但我從來沒有得到你描述的例外。我測試了本地和域帳戶,但ProtectedData.Protect總是成功。祝你好運,我有興趣聽到如果你找到解決方案... – 2010-03-24 12:32:41

+0

@rwwilden:解除保護,而不是保護。 – 2010-03-24 13:53:25

0

這裏是發生了什麼事情:爲DPAPI的工作,它需要這部分得自用戶的登錄憑據用戶的密鑰材料。該數據與用戶的配置文件一起存儲。這就是爲什麼一個進程沒有運行,因爲用戶必須加載用戶的配置文件。

必須調用使用從LoadUserProfile(返回)數據

這裏就是你需要做什麼UnloadUserProfile())))

LogonUser的(
冒充(
LoadUserProfile(
加密( )
UnloadUserProfile()
RevertImpersonation()(撤消()在.NET)

必須檢查錯誤,使用GetLastError函數()的每一步。

請注意,爲你所有這些東西基本上都是需要過程是管理員帳戶。您需要備份和還原權限才能加載用戶的配置文件。如果在調用LoadUserProfile當你得到一個特權不持有錯誤,那麼你需要:

一)確保應用程序帳戶具有備份和恢復PRIVS
二)PRIVS啓用,默認情況下它們都沒有。

可以使用AdjustTokenPrivileges()http://msdn.microsoft.com/en-us/library/aa375202(VS.85).aspx