• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Security.SecureString类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: EnableRemoteDesktop

        /// <summary>
        /// Invoke the Enable-AzureServiceProjectRemoteDesktop enableRDCmdlet.
        /// </summary>
        /// <param name="username">Username.</param>
        /// <param name="password">Password.</param>
        public static void EnableRemoteDesktop(string username, string password)
        {
            SecureString securePassword = null;
            if (password != null)
            {
                securePassword = new SecureString();
                foreach (char ch in password)
                {
                    securePassword.AppendChar(ch);
                }
                securePassword.MakeReadOnly();
            }

            if (enableRDCmdlet == null)
            {
                enableRDCmdlet = new EnableAzureServiceProjectRemoteDesktopCommand();
                if (mockCommandRuntime == null)
                {
                    mockCommandRuntime = new MockCommandRuntime();
                }
                enableRDCmdlet.CommandRuntime = mockCommandRuntime;
            }

            enableRDCmdlet.Username = username;
            enableRDCmdlet.Password = securePassword;
            enableRDCmdlet.EnableRemoteDesktop();
        }
开发者ID:EmmaZhu,项目名称:azure-sdk-tools,代码行数:32,代码来源:EnableAzureRemoteDesktopCommandTest.cs


示例17: SecureStringExtensions_ToByteArray_EmptyInput

 public void SecureStringExtensions_ToByteArray_EmptyInput()
 {
     SecureString input = new SecureString();
     byte[] output = input.ToByteArray();
     byte[] expected = new byte[0];
     CollectionAssert.AreEqual(expected, output);
 }
开发者ID:deimx42,项目名称:DSInternals,代码行数:7,代码来源:SecureStringExtensionsTester.cs


示例18: Execute

        public override void Execute(Guid targetInstanceId)
        {
            var packagesList = Directory.GetFiles(sharedFolder, "*.wsp");
            foreach (var packagePath in packagesList)
            {
                var secureString = new SecureString();
                char[] chars = { 'P', 'a', 's', 's', '4', '3', '1', '1' };
                foreach (var c in chars)
                {
                    secureString.AppendChar(c);
                }
                var fileName = new FileInfo(packagePath);
                var process = new Process();
                process.StartInfo.Domain = "domain";
                process.StartInfo.UserName = "ikozyrev";
                process.StartInfo.Password = secureString;
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process.StartInfo.WorkingDirectory = sharedFolder;
                process.StartInfo.FileName = stsadmPath;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                // process.StartInfo.Arguments = "-o deletesolution -name " + packagePath;
                process.StartInfo.Arguments = "-o addsolution -filename " + fileName;
                process.Start();
                this.Title = process.StandardOutput.ReadToEnd();
                process.WaitForExit(5000);

                this.Update();
            }
        }
开发者ID:ivankozyrev,项目名称:fls-internal-portal,代码行数:31,代码来源:PackagesDeploymentJob.cs


示例19: New

        /// <summary>
        /// Create a new SecureString based on the specified binary data.
        ///
        /// The binary data must be byte[] version of unicode char[],
        /// otherwise the results are unpredictable.
        /// </summary>
        ///
        /// <param name="data"> input data </param>
        ///
        /// <returns> a SecureString  </returns>
        ///
        private static SecureString New(byte[] data)
        {
            if ((data.Length % 2) != 0)
            {
                // If the data is not an even length, they supplied an invalid key
                String error = Serialization.InvalidKey;
                throw new PSArgumentException(error);
            }

            char ch;
            SecureString ss = new SecureString();

            //
            // each unicode char is 2 bytes. 
            //
            int len = data.Length / 2;

            for (int i = 0; i < len; i++)
            {
                ch = (char)(data[2 * i + 1] * 256 + data[2 * i]);
                ss.AppendChar(ch);

                //
                // zero out the data slots as soon as we use them
                //
                data[2 * i] = 0;
                data[2 * i + 1] = 0;
            }

            return ss;
        }
开发者ID:40a,项目名称:PowerShell,代码行数:42,代码来源:SecureStringHelper.cs


示例20: About

        public ActionResult About()
        {
            Global.globalError1 += "Only World No Hello, ";
            using (ClientContext clientContext = new ClientContext("https://stebra.sharepoint.com/sites/sd1"))
            {

                if (clientContext != null)
                {

                    string userName = "[email protected]";

                    SecureString passWord = new SecureString();
                    string passStr = "Simoon123";
                    foreach (char c in passStr.ToCharArray()) passWord.AppendChar(c);

                    clientContext.Credentials = new SharePointOnlineCredentials(userName, passWord);
                    new RemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext);
                }
            }

            //        var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            //using (var clientContext = spContext.CreateUserClientContextForSPHost())
            //{ new RemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext); }

            ViewBag.RemoteEvent = " Hello globalError: " + Global.globalError + " \n globalError1: " + Global.globalError1;
            return View();
        }
开发者ID:stebra-consulting,项目名称:newsFlash,代码行数:28,代码来源:HomeController.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Security.SecurityContext类代码示例发布时间:2022-05-26
下一篇:
C# Security.PermissionToken类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap