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


C# SecureString.ConvertToUnsecureString方法代码示例

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


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

示例1: CreateUser

        public ApplicationUser CreateUser(string username, SecureString password, bool isAdmin = false, bool isReadOnly = false)
        {
            string unsecuredPasswordString = password.ConvertToUnsecureString();
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(unsecuredPasswordString))
                return null;

            ApplicationUser user = new ApplicationUser();
            using (var db = new TestcaseManagerDB())
            {
                user.Username = username;
                string encryptedValue = cryptoService.Encrypt(unsecuredPasswordString);
                user.Password = encryptedValue;

                if(isReadOnly)
                    user.IsReadOnly = true;

                if(isAdmin)
                    user.IsAdmin = true;

                user.CreatedBy = AuthenticationManager.Instance().GetCurrentUsername;
                user.CreatedOn = DateTime.UtcNow;

                db.ApplicationUsers.Add(user);
                db.SaveChanges();
            }

            return user;
        }
开发者ID:vaptsarov,项目名称:Diploma-thesis,代码行数:28,代码来源:UserManager.cs

示例2: 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

示例3: ConvertToUnsecureString_ReturnsString

        public void ConvertToUnsecureString_ReturnsString()
        {
            // Assemble
            var secureString = new SecureString();
            var insecureString = "teenagers";
            foreach (var c in insecureString)
            {
                secureString.AppendChar(c);
            }

            // Act
            var actual = secureString.ConvertToUnsecureString();

            // Assert
            Assert.AreEqual(insecureString, actual);
        }
开发者ID:joashmusyoka,项目名称:spikes,代码行数:16,代码来源:SecureStringTests.cs

示例4: Decrypt

        public string Decrypt(string ciphertextBase64, SecureString password)
        {
            if (string.IsNullOrEmpty(ciphertextBase64) || password.Length == 0)
                return ciphertextBase64;

            try
            {
                var plaintext = "";

                using (var rijndaelManaged = new RijndaelManaged())
                {
                    using (var md5 = new MD5CryptoServiceProvider())
                    {
                        var key = md5.ComputeHash(Encoding.UTF8.GetBytes(password.ConvertToUnsecureString()));
                        rijndaelManaged.Key = key;
                    }

                    var ciphertext = Convert.FromBase64String(ciphertextBase64);

                    var memoryStream = new MemoryStream(ciphertext);
                    var iv = new byte[BlockSizeInBytes];
                    memoryStream.Read(iv, 0, iv.Length);
                    rijndaelManaged.IV = iv;

                    var cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(), CryptoStreamMode.Read);
                    using (var streamReader = new StreamReader(cryptoStream, Encoding.UTF8, true))
                    {
                        plaintext = streamReader.ReadToEnd();
                        rijndaelManaged.Clear();
                    }
                } // rijndaelManaged

                return plaintext;
            }
            catch (Exception ex)
            {
                //Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, string.Format(Language.strErrorDecryptionFailed, ex.Message));
                throw new EncryptionException(Language.strErrorDecryptionFailed, ex);
            }
        }
开发者ID:mRemoteNG,项目名称:mRemoteNG,代码行数:40,代码来源:LegacyRijndaelCryptographyProvider.cs

示例5: Login_Internal

        /// <summary>
        /// Logs in and returns the session ID
        /// </summary>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private PkildSession Login_Internal(String user, 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 requestData = String.Format(
                    "username={0}&password={1}&login=Submit",
                    HttpUtility.UrlEncode(user, Encoding.UTF8),
                    HttpUtility.UrlEncode(password.ConvertToUnsecureString(), Encoding.UTF8));
                writer.Write(requestData);
                requestData.Zero();
            }

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                    throw new Exception("Failed to log in: Server returned status code " + response.StatusCode.ToString());

                String cookies = response.Headers[HttpResponseHeader.SetCookie];

                using (Stream responseStream = response.GetResponseStream())
                {
                    var parser = new ResponseParser(new StreamReader(responseStream).ReadToEnd());
                    certRevokeNode = parser.RevocationNodeName;
                    CertificateState = parser.CertificateState;
                }
                
                if (cookies.ToString().StartsWith("pkild_session"))
                    return new PkildSession(cookies.ToString());

                throw new Exception("Unexpected response from server");
            }
        }
开发者ID:Kintar,项目名称:pkild.net,代码行数:44,代码来源:PkildClient.cs

示例6: ChangePassword

 // Private methods.
 /// <summary>
 /// Changes the current password of the database server.
 /// </summary>
 /// <param name="newPassword">The new password.</param>
 private void ChangePassword(SecureString newPassword)
 {
     lock (this.sync)
     {
         try
         {
             // Initialize the server.
             this.OnInitialized();
             // Change the server password.
             SqlConnection.ChangePassword(this.connectionString.ConnectionString, newPassword.ConvertToUnsecureString());
             // If the password change was successfull, update the configuration.
             this.Password = newPassword;
             // Log the event.
             this.LogEvent(
                 LogEventLevel.Verbose,
                 LogEventType.Information,
                 "Changing the password for the database server with ID \'{0}\' completed successfully.",
                 new object[] { this.Id }
                 );
             // Save the configuration.
             this.SaveConfiguration();
         }
         catch (Exception exception)
         {
             // Log the event.
             this.LogEvent(
                 LogEventLevel.Important,
                 LogEventType.Error,
                 "Changing the password for the database server with ID \'{0}\' failed. {1}",
                 new object[] { this.Id, exception.Message },
                 exception
                 );
             // Rethrow the exception.
             throw;
         }
     }
 }
开发者ID:alexbikfalvi,项目名称:InetAnalytics,代码行数:42,代码来源:DbServerMsSql.cs

示例7: Ok

 public void Ok(SecureString securePassword)
 {
     PasswordHash = securePassword.ConvertToUnsecureString().ToMd5Hash();
     TryClose(true);
 }
开发者ID:ebeeb,项目名称:SfSdk,代码行数:5,代码来源:CreateAccountViewModel.cs

示例8: UpdateUser

        public ApplicationUser UpdateUser(int id, string username, SecureString password, bool isAdmin = false, bool isReadOnly = false)
        {
            if (string.IsNullOrEmpty(username))
                return null;

            ApplicationUser user;
            using (var db = new TestcaseManagerDB())
            {
                user = db.ApplicationUsers.Where(u => u.UserId.Equals(id)).FirstOrDefault();
                if (user != null)
                {
                    user.Username = username;

                    string unsecuredPasswordString = password.ConvertToUnsecureString();
                    if (string.IsNullOrWhiteSpace(unsecuredPasswordString) == false)
                    {
                        string encryptedValue = cryptoService.Encrypt(unsecuredPasswordString);
                        user.Password = encryptedValue;
                    }

                    user.IsAdmin = isAdmin;
                    user.UpdatedBy = AuthenticationManager.Instance().GetCurrentUsername;

                    db.SaveChanges();
                }
            }

            return user;
        }
开发者ID:vaptsarov,项目名称:Diploma-thesis,代码行数:29,代码来源:UserManager.cs

示例9: GetUser

        public ApplicationUser GetUser(string username, SecureString password)
        {
            string unsecuredPasswordString = password.ConvertToUnsecureString();
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(unsecuredPasswordString))
                throw new ArgumentException("Username or password was empty or null.");

            ApplicationUser user = null;
            using (var db = new TestcaseManagerDB())
            {
                var users = db.ApplicationUsers.Where(usr => usr.Username == username).ToList();

                foreach (var usr in users)
                {
                    string decryptedPassword = cryptoService.Decrypt(usr.Password);
                    if (decryptedPassword == unsecuredPasswordString)
                    {
                        user = usr;
                        break;
                    }
                }
            }

            if (user == null)
                throw new ArgumentNullException("User with the provided credentials was not found.");

            return user;
        }
开发者ID:vaptsarov,项目名称:Diploma-thesis,代码行数:27,代码来源:UserManager.cs

示例10: Encrypt

        public string Encrypt(string strToEncrypt, SecureString strSecret)
        {
            if (strToEncrypt == "" || strSecret.Length == 0)
                return strToEncrypt;

            try
            {
                var rd = new RijndaelManaged();

                var md5 = new MD5CryptoServiceProvider();
                var key = md5.ComputeHash(Encoding.UTF8.GetBytes(strSecret.ConvertToUnsecureString()));

                md5.Clear();
                rd.Key = key;
                rd.GenerateIV();

                var iv = rd.IV;
                var ms = new MemoryStream();

                ms.Write(iv, 0, iv.Length);

                var cs = new CryptoStream(ms, rd.CreateEncryptor(), CryptoStreamMode.Write);
                var data = Encoding.UTF8.GetBytes(strToEncrypt);

                cs.Write(data, 0, data.Length);
                cs.FlushFinalBlock();

                var encdata = ms.ToArray();
                cs.Close();
                rd.Clear();

                return Convert.ToBase64String(encdata);
            }
            catch (Exception ex)
            {
                Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, string.Format(Language.strErrorEncryptionFailed, ex.Message));
            }

            return strToEncrypt;
        }
开发者ID:mRemoteNG,项目名称:mRemoteNG,代码行数:40,代码来源:LegacyRijndaelCryptographyProvider.cs

示例11: SetContextUser

 private void SetContextUser(string username, SecureString password)
 {
     client = new GitHubClient(new ProductHeaderValue("CustomApplication"));
     client.Credentials = new Credentials(username, password.ConvertToUnsecureString());
 }
开发者ID:vaptsarov,项目名称:Diploma-thesis,代码行数:5,代码来源:IssueManager.cs


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