Advertisement
Guest User

Untitled

a guest
Jan 9th, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. [DllImport("coredll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  2. static extern int CredWrite([In]IntPtr pCred, [In]CREDWRITE_FLAGS dwflags);
  3.  
  4. public enum CREDWRITE_FLAGS : int
  5. {
  6. CRED_FLAG_FAIL_IF_EXISTING = 0x00000400
  7. }
  8.  
  9. public struct CRED
  10. {
  11. public int dwVersion;
  12. public CRED_TYPE dwType;
  13. [MarshalAs(UnmanagedType.LPWStr)]
  14. public string wszUser;
  15. public int dwUserLen;
  16. [MarshalAs(UnmanagedType.LPWStr)]
  17. public string wszTarget;
  18. public int dwTargetLen;
  19. public IntPtr pBlob;
  20. public int dwBlobSize;
  21. public CRED_FLAGS dwFlags;
  22. }
  23. public enum CRED_TYPE
  24. {
  25. CRED_TYPE_NTLM = 0x00010002,
  26. CRED_TYPE_KERBEROS = 0x00010004,
  27. CRED_TYPE_PLAINTEXT_PASSWORD = 0x00010006,
  28. CRED_TYPE_CERTIFICATE = 0x00010008,
  29. CRED_TYPE_GENERIC = 0x0001000a,
  30. CRED_TYPE_DOMAIN_PASSWORD = 0x00010001,
  31. }
  32. public enum CRED_FLAGS : int
  33. {
  34. CRED_FLAG_PERSIST = 0x00000001,
  35. CRED_FLAG_DEFAULT = 0x00000002,
  36. CRED_FLAG_SENSITIVE = 0x00000008,
  37. CRED_FLAG_TRUSTED = 0x00000010
  38. }
  39.  
  40. public static void WriteCredentials(string target, string userName, string password)
  41. {
  42. CRED cred = new CRED();
  43. cred.dwVersion = 1;
  44. cred.dwType = CRED_TYPE.CRED_TYPE_NTLM;
  45. cred.wszTarget = target;
  46. cred.dwTargetLen = target.Length + 1;
  47. cred.wszUser = userName;
  48. cred.dwUserLen = userName.Length + 1;
  49.  
  50. cred.dwBlobSize = (Encoding.Unicode.GetBytes(password).Length + 1) * 2;
  51. //cred.pBlob = Marshal.StringToCoTaskMemUni(password); //<--not in CF
  52. //cred.pBlob = Marshal2.StringToHGlobalUni(password); //<--from OpenNETCF, the same?
  53. cred.pBlob = Marshal.StringToBSTR(password); //<--not sure of that, but tried the other one also
  54. cred.dwFlags = CRED_FLAGS.CRED_FLAG_PERSIST | CRED_FLAGS.CRED_FLAG_SENSITIVE | CRED_FLAGS.CRED_FLAG_TRUSTED; //<-- results in 25 which is also used in creds read which are stored by the IE-UI-CredMan-dialog
  55.  
  56. IntPtr credPtr = Marshal.AllocHGlobal(Marshal.SizeOf(cred));
  57. Marshal.StructureToPtr(cred, credPtr, true);
  58.  
  59. int ret = -1;
  60. ret = CredWrite(credPtr, CREDWRITE_FLAGS.CRED_FLAG_FAIL_IF_EXISTING); //returns zero, unless called twice with the same target/username-tuple.
  61.  
  62. Marshal.FreeHGlobal(credPtr);
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement