示例#1
0
        private static bool SaveCredential(Credential credential, string password)
        {
            var passwordUnicodeBytesLength = (uint)Encoding.Unicode.GetBytes(password).Length;

            var nativePassword = Marshal.StringToHGlobalUni(password);

            var nativeCredential = new Marshaler.NativeCredential
            {
                Flags              = credential.Flags,
                Type               = credential.Type,
                TargetName         = credential.TargetName,
                CredentialBlob     = nativePassword,
                CredentialBlobSize = passwordUnicodeBytesLength,
                Persist            = credential.Persist,
                UserName           = credential.UserName
            };

            var result = NativeInterop.CredWrite(nativeCredential, 0);

            return(result);
        }
示例#2
0
        private static IEnumerable <Credential> EnumerateCredentials()
        {
            IntPtr data = default;

            try
            {
                var result = NativeInterop.CredEnumerate(null, 0, out var count, out data);

                if (!result)
                {
                    return(null);
                }

                var credentials = new List <Credential>();

                for (var index = 0; index < count; index++)
                {
                    var currentData    = Marshal.ReadIntPtr(data + index * Marshal.SizeOf <IntPtr>());
                    var marshallResult = Marshaler.MarshalCredentialInstance(currentData);
                    if (marshallResult.IsSuccess)
                    {
                        credentials.Add(marshallResult.Value);
                    }
                    // TODO Add logging and log a warning if marshalling fails
                }

                return(credentials);
            }
            finally
            {
                if (data != IntPtr.Zero)
                {
                    NativeInterop.CredFree(data);
                }
            }
        }