本文整理汇总了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;
}
示例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;
}
}
}
示例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);
}
示例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);
}
}
示例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");
}
}
示例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;
}
}
}
示例7: Ok
public void Ok(SecureString securePassword)
{
PasswordHash = securePassword.ConvertToUnsecureString().ToMd5Hash();
TryClose(true);
}
示例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;
}
示例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;
}
示例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;
}
示例11: SetContextUser
private void SetContextUser(string username, SecureString password)
{
client = new GitHubClient(new ProductHeaderValue("CustomApplication"));
client.Credentials = new Credentials(username, password.ConvertToUnsecureString());
}