当前位置: 首页>>代码示例>>C#>>正文


C# Security.SecureString类代码示例

本文整理汇总了C#中System.Security.SecureString的典型用法代码示例。如果您正苦于以下问题:C# SecureString类的具体用法?C# SecureString怎么用?C# SecureString使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


SecureString类属于System.Security命名空间,在下文中一共展示了SecureString类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CredToken

 public CredToken(string domain, string user, SecureString Password, bool canimpersonate)
 {
     _usr = user;
     _domain = domain;
     _pw = Password;
     _canImpersonate = canimpersonate;
 }
开发者ID:ZXeno,项目名称:Andromeda,代码行数:7,代码来源:CredToken.cs

示例2: EventLogSession

 public EventLogSession(string server, string domain, string user, SecureString password, SessionAuthentication logOnType)
 {
     this.renderContextHandleSystem = EventLogHandle.Zero;
     this.renderContextHandleUser = EventLogHandle.Zero;
     this.handle = EventLogHandle.Zero;
     EventLogPermissionHolder.GetEventLogPermission().Demand();
     if (server == null)
     {
         server = "localhost";
     }
     this.syncObject = new object();
     this.server = server;
     this.domain = domain;
     this.user = user;
     this.logOnType = logOnType;
     Microsoft.Win32.UnsafeNativeMethods.EvtRpcLogin login = new Microsoft.Win32.UnsafeNativeMethods.EvtRpcLogin {
         Server = this.server,
         User = this.user,
         Domain = this.domain,
         Flags = (int) this.logOnType,
         Password = CoTaskMemUnicodeSafeHandle.Zero
     };
     try
     {
         if (password != null)
         {
             login.Password.SetMemory(Marshal.SecureStringToCoTaskMemUnicode(password));
         }
         this.handle = NativeWrapper.EvtOpenSession(Microsoft.Win32.UnsafeNativeMethods.EvtLoginClass.EvtRpcLogin, ref login, 0, 0);
     }
     finally
     {
         login.Password.Close();
     }
 }
开发者ID:nickchal,项目名称:pash,代码行数:35,代码来源:EventLogSession.cs

示例3: CreateCertificate

        public byte[] CreateCertificate(SecureString password)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseUri);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers[HttpRequestHeader.Cookie] = "pkild_session=" + Session.SessionID;
            using (Stream reqStream = request.GetRequestStream())
            using (StreamWriter writer = new StreamWriter(reqStream))
            {
                String parameters = String.Format("password={0}&confirm_password={0}&submit=create&action_type=pkcs12_cert",
                    HttpUtility.UrlEncode(password.ConvertToUnsecureString()));
                writer.Write(parameters);
                parameters.Zero();
            }

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                    throw new Exception("Bad response code: " + response.StatusCode);

                if (response.ContentType != "application/x-pkcs12")
                    return FetchCertificate();

                using (Stream responseStream = response.GetResponseStream())
                {
                    byte[] certBytes = new byte[response.ContentLength];
                    responseStream.Read(certBytes, 0, certBytes.Length);
                    CertificateState = CertificateState.Present;
                    return certBytes;
                }
            }
        }
开发者ID:Kintar,项目名称:pkild.net,代码行数:33,代码来源:PkildClient.cs

示例4: EnterPassword

 public static SecureString EnterPassword()
 {
     SecureString pwd = new SecureString();
     while (true)
     {
         ConsoleKeyInfo i = Console.ReadKey(true);
         if (i.Key == ConsoleKey.Enter)
         {
             break;
         }
         else if (i.Key == ConsoleKey.Backspace)
         {
             if (pwd.Length > 0)
             {
                 pwd.RemoveAt(pwd.Length - 1);
                 Console.Write("\b \b");
             }
         }
         else
         {
             pwd.AppendChar(i.KeyChar);
             Console.Write("*");
         }
     }
     return pwd;
 }
开发者ID:heimanhon,项目名称:researchwork,代码行数:26,代码来源:Utilities.cs

示例5: Write

        /// <summary>
        /// Note: this doesn't keep the SecureString secure.
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="secure"></param>
        public static void Write(this BinaryWriter writer, SecureString secure)
        {
            var bwx = new BinaryWriterEx(writer.BaseStream);

            byte[] utf16 = new byte[secure.Length * 2];

            var ptr = Marshal.SecureStringToBSTR(secure);
            var len = Marshal.ReadInt32(ptr, -4);

            for (int i = 0; i < len; i += 2)
            {
                utf16[i] = Marshal.ReadByte(ptr, i);
            }

            Marshal.ZeroFreeBSTR(ptr);

            byte[] utf8 = UTF8Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16);

            for (int i = 0; i < utf16.Length; i++)
            {
                utf16[i] = 0; // clear memory
            }

            bwx.Write7BitEncodedInt(utf8.Length);
            for (int i = 0; i < utf8.Length; i++)
            {
                bwx.Write(utf8[i]);
                utf8[i] = 0;
            }
        }
开发者ID:wfraser,项目名称:FooSync,代码行数:35,代码来源:NetUtil.cs

示例6: SetAzureAutomationCredentialByNameWithParametersSuccessfull

        public void SetAzureAutomationCredentialByNameWithParametersSuccessfull()
        {
            // Setup
            string accountName = "automation";
            string credentialName = "credential";
            string username = "testUser";
            string password = "password";
            string description = "desc";

            var secureString = new SecureString();
            Array.ForEach(password.ToCharArray(), secureString.AppendChar);
            secureString.MakeReadOnly();

            var value = new PSCredential(username, secureString);

            this.mockAutomationClient.Setup(f => f.UpdateCredential(accountName, credentialName, username, password, description));

            // Test
            this.cmdlet.AutomationAccountName = accountName;
            this.cmdlet.Name = credentialName;
            this.cmdlet.Description = description;
            this.cmdlet.Value = value;
            this.cmdlet.ExecuteCmdlet();

            // Assert
            this.mockAutomationClient.Verify(f => f.UpdateCredential(accountName, credentialName, username, password, description), Times.Once());
        }
开发者ID:docschmidt,项目名称:azure-powershell,代码行数:27,代码来源:SetAzureAutomationCredentialTest.cs

示例7: SPService

        public SPService(string username, string password, string url)
        {
            using (ClientContext ctx = new ClientContext(url))
            {
                var securePassword = new SecureString();
                foreach (char c in password)
                {
                    securePassword.AppendChar(c);
                }

                var onlineCredentials = new SharePointOnlineCredentials(username, securePassword);
                
                ctx.Credentials = onlineCredentials;
                web = ctx.Web;
                ctx.Load(web);
                ctx.ExecuteQuery();
                //ctx.GetFormDigestDirect().DigestValue
                var authCookie = onlineCredentials.GetAuthenticationCookie(new Uri(url));
                //var fedAuthString = authCookie.TrimStart("SPOIDCRL=".ToCharArray());
                
                webinfo = new WebInfo { Title = web.Title, ErrorMessage = "", DigestInfo = authCookie.ToString() };
                
                context = ctx;
            }
        }
开发者ID:maxali,项目名称:search-addin,代码行数:25,代码来源:SPService.cs

示例8: StorePerUserCredentials

        /// <summary>
        /// This function stores user credentials using the Windows Data Protection API
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public static void StorePerUserCredentials(string userName, SecureString password, string fileName, string keyName)
        {
            // Generate additional entropy (will be used as the Initialization vector)
            // This is basically the (2048-bit) encryption key used to encrypt the credentials
            // The encryption key changes everytime the credentials get stored for increased security (everytime someone logs in with "Remember Me" ticked)
            byte[] entropy = new byte[256];
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(entropy);
            }

            var currentUserRegistry = Registry.CurrentUser.OpenSubKey("Software\\SystemsUnitedNavy", true);
            if (currentUserRegistry == null)
                currentUserRegistry = Registry.CurrentUser.CreateSubKey("Software\\SystemsUnitedNavy", RegistryKeyPermissionCheck.Default);

            currentUserRegistry.SetValue(keyName, entropy);


            var data = ProtectedData.Protect(StringToByteArray(string.Format("{0};#{1}",
                userName, SecureStringUtility.SecureStringToString(password))),
                entropy,
                DataProtectionScope.CurrentUser);

            File.WriteAllBytes(fileName, data);
        }
开发者ID:RononDex,项目名称:Sun.Plasma,代码行数:30,代码来源:SecureStorage.cs

示例9: GetCertFromPfxFile

		private static X509Certificate2 GetCertFromPfxFile(string path, SecureString password)
		{
			X509Certificate2 x509Certificate2 = new X509Certificate2();
			string stringFromSecureString = SecurityUtils.GetStringFromSecureString(password);
			x509Certificate2.Import(path, stringFromSecureString, X509KeyStorageFlags.DefaultKeySet);
			return x509Certificate2;
		}
开发者ID:nickchal,项目名称:pash,代码行数:7,代码来源:GetPfxCertificateCommand.cs

示例10: ExecuteNonQueryProcedure

        public void ExecuteNonQueryProcedure(string procedureName, System.Collections.Specialized.NameValueCollection parametersCollection)
        {
            try
            {
                string password = "wolfstein";
                var pwdarr = password.ToCharArray();
                SecureString securePwd = new SecureString();
                foreach (char c in pwdarr)
                {
                    securePwd.AppendChar(c);
                }
                securePwd.MakeReadOnly();

                using (
                    SqlConnection conn = new SqlConnection(this.db.Database.Connection.ConnectionString))
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandText = procedureName;
                    cmd.CommandType = CommandType.StoredProcedure;
                    foreach (var key in parametersCollection.AllKeys)
                    {
                        cmd.Parameters.AddWithValue(key, parametersCollection[key]);
                    }
                    var result = cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
开发者ID:yuyi1,项目名称:Verdezyne-Operations,代码行数:33,代码来源:PilotPlantStoredProcedure.cs

示例11: GetStringFromSecureString

		internal static string GetStringFromSecureString(SecureString ss)
		{
			IntPtr globalAllocUnicode = Marshal.SecureStringToGlobalAllocUnicode(ss);
			string stringUni = Marshal.PtrToStringUni(globalAllocUnicode);
			Marshal.ZeroFreeGlobalAllocUnicode(globalAllocUnicode);
			return stringUni;
		}
开发者ID:nickchal,项目名称:pash,代码行数:7,代码来源:SecurityUtils.cs

示例12: NewUserModel

 public NewUserModel(string firstName, string lastName, string username, SecureString password)
 {
     this.FirstName = firstName;
     this.LastName = lastName;
     this.Username = username;
     this.Password = password;
 }
开发者ID:mmarkovic,项目名称:StockTicker,代码行数:7,代码来源:NewUserModel.cs

示例13: MingleServer

 /// <summary>
 /// Constructs a new MingleServer
 /// </summary>
 /// <param name="hostUrl">Host url</param>
 /// <param name="loginName">Login name of the user</param>
 /// <param name="password">password</param>
 public MingleServer(string hostUrl, string loginName, string password)
 {
     _host = hostUrl;
     _login = loginName;
     _password = new SecureString();
     foreach (var c in password.ToCharArray()) _password.AppendChar(c);
 } 
开发者ID:ThoughtWorksStudios,项目名称:mingle.net,代码行数:13,代码来源:MingleServer.cs

示例14: AuthIdentity

        // constructors
        public AuthIdentity(string username, SecureString password)
        {
            Username = null;
            UsernameLength = 0;
            if (!string.IsNullOrEmpty(username))
            {
                Username = username;
                UsernameLength = username.Length;
            }

            Password = IntPtr.Zero;
            PasswordLength = 0;
            
            if (password != null && password.Length > 0)
            {
#if NET45
                Password = Marshal.SecureStringToGlobalAllocUnicode(password);
#else
                Password = SecureStringMarshal.SecureStringToGlobalAllocUnicode(password);
#endif
                PasswordLength = password.Length;
            }

            Domain = null;
            DomainLength = 0;

            Flags = AuthIdentityFlag.Unicode;
        }
开发者ID:mfidemraizer,项目名称:mongo-csharp-driver,代码行数:29,代码来源:AuthIdentity.cs

示例15: OnLogin

        public void OnLogin(string server, int port, string account, SecureString password)
        {
            m_Login.Client.UserName = account;
            m_Login.Client.Password = password;

            Manager.CurrentState = new LoggingInState();
        }
开发者ID:InjectionDev,项目名称:UltimaXNA,代码行数:7,代码来源:LoginState.cs


注:本文中的System.Security.SecureString类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。