Beispiel #1
0
        /// <summary>
        /// Stores a credential in the Windows Credential Manager on the local machine.
        /// </summary>
        /// <param name="target">The target name of the credential.</param>
        /// <param name="key">The credential key.</param>
        internal static void StoreCredential(string target, string key)
        {
            CREDENTIAL cred = new CREDENTIAL();

            cred.Type    = (int)CRED_TYPE.GENERIC;
            cred.Persist = (int)CRED_PERSIST.LOCAL_MACHINE;

            cred.TargetName         = target;
            cred.UserName           = target;
            cred.CredentialBlob     = Marshal.StringToHGlobalUni(key);
            cred.CredentialBlobSize = key.Length * 2; // Multiply by 2 since we're using Unicode chars

            if (!CredWrite(ref cred, 0))
            {
                int lastError = Marshal.GetLastWin32Error();
                throw new InvalidOperationException(string.Format("Failed to store credential for {0}. Last error: {1}", target, lastError));
            }
        }
Beispiel #2
0
 private static extern bool CredWrite(ref CREDENTIAL credential, int flags);