예제 #1
0
        public static PSCredential Read(string target, CredType type, string userName)
        {
            IntPtr credentialPtr;

            if (!NativeMethod.CredRead(target, type, 0, out credentialPtr))
            {
                throw new NullReferenceException("Failed to find credentials in Windows Credential Manager. TargetName: {0}, Type {1}");
            }

            using (var handler = new NativeMethod.CriticalCredentialHandle(credentialPtr))
            {
                var result = GetNetworkCredential(handler, userName);
                return(result);
            }
        }
예제 #2
0
        private static PSCredential GetNetworkCredential(NativeMethod.CriticalCredentialHandle handler, string userName)
        {
            var credential = handler.GetCredential();

            if (string.IsNullOrWhiteSpace(userName))
            {
                userName = credential.UserName;
            }
            var secureString = new System.Security.SecureString();

            foreach (var c in credential.CredentialBlob)
            {
                secureString.AppendChar(c);
            }
            var psCredential = new PSCredential(userName, secureString);

            return(psCredential);
        }