static bool WriteCredential (string targetName, string userName, string password) { if (targetName == null) throw new ArgumentNullException ("targetName"); if (userName == null) throw new ArgumentNullException ("userName"); if (password == null) throw new ArgumentNullException ("password"); var passwordBytes = Encoding.Unicode.GetBytes (password); if (passwordBytes.Length > 512) throw new ArgumentException ("The secret message has exceeded 512 bytes."); // Go ahead with what we have are stuff it into the CredMan structures. var cred = new Credential { TargetName = targetName, CredentialBlob = password, CredentialBlobSize = (UInt32) passwordBytes.Length, AttributeCount = 0, Attributes = IntPtr.Zero, Comment = null, TargetAlias = null, Type = NativeCredentialType.Generic, Persist = PersistFlags.LocalMachine, UserName = userName, }; var ncred = NativeCredential.GetNativeCredential (cred); // Write the info into the CredMan storage. var didWrite = NativeMethods.CredWrite (ref ncred, 0); Marshal.FreeCoTaskMem (ncred.TargetName); Marshal.FreeCoTaskMem (ncred.CredentialBlob); Marshal.FreeCoTaskMem (ncred.UserName); return didWrite; }
/// <summary> /// This method derives a NativeCredential instance from a given Credential instance. /// </summary> /// <param name="cred">The managed Credential counterpart containing data to be stored.</param> /// <returns>A NativeCredential instance that is derived from the given Credential /// instance.</returns> internal static NativeCredential GetNativeCredential (Credential cred) { return new NativeCredential { AttributeCount = 0, Attributes = IntPtr.Zero, Comment = IntPtr.Zero, TargetAlias = IntPtr.Zero, Type = NativeCredentialType.Generic, Persist = (UInt32)PersistFlags.LocalMachine, CredentialBlobSize = cred.CredentialBlobSize, TargetName = Marshal.StringToCoTaskMemUni (cred.TargetName), CredentialBlob = Marshal.StringToCoTaskMemUni (cred.CredentialBlob), UserName = Marshal.StringToCoTaskMemUni (cred.UserName) }; }