本文整理汇总了C#中System.Security.SecureString.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# SecureString.Dispose方法的具体用法?C# SecureString.Dispose怎么用?C# SecureString.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.SecureString
的用法示例。
在下文中一共展示了SecureString.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: check_log
private void check_log(string name) {
try {
SecureString pwd = new SecureString();
foreach ( char c in remote_passw_)
pwd.AppendChar(c);
EventLogSession session = remote_machine_name_ != "" ? new EventLogSession(remote_machine_name_, remote_domain_, remote_username_, pwd, SessionAuthentication.Default) : null;
pwd.Dispose();
string query_string = "*";
EventLogQuery query = new EventLogQuery(name, PathType.LogName, query_string);
using (EventLogReader reader = new EventLogReader(query))
for (EventRecord rec = reader.ReadEvent(); rec != null; rec = reader.ReadEvent())
lock (this)
--log_names_[name];
} catch (Exception e) {
logger.Error("error checking log " + name + " on " + remote_machine_name_ + " : " + e.Message);
}
// mark log as fully read
lock (this) {
log_names_[name] = -log_names_[name];
if (log_names_[name] == 0)
// convention - 0 entries
log_names_[name] = int.MinValue;
}
}
示例2: ReadPasswordFromConsole
/// <summary>
/// Read a password from the console and return it as SecureString
/// </summary>
/// <returns></returns>
public static bool ReadPasswordFromConsole(out SecureString secStr)
{
secStr = new SecureString();
for (ConsoleKeyInfo c = Console.ReadKey(true); c.Key != ConsoleKey.Enter; c = Console.ReadKey(true))
{
if (c.Key == ConsoleKey.Backspace && secStr.Length > 0)
secStr.RemoveAt(secStr.Length - 1);
if (c.Key == ConsoleKey.Escape)
{
// cancel
secStr.Dispose();
Console.WriteLine();
return false;
}
if (!Char.IsControl(c.KeyChar))
secStr.AppendChar(c.KeyChar);
}
secStr.MakeReadOnly();
Console.WriteLine();
return true;
}
示例3: GetSecureStringFromConsole
public static SecureString GetSecureStringFromConsole()
{
var password = new SecureString();
Console.Write("Enter Password: ");
while (true)
{
ConsoleKeyInfo cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Enter) break;
if (cki.Key == ConsoleKey.Escape)
{
password.Dispose();
return null;
}
if (cki.Key == ConsoleKey.Backspace)
{
if (password.Length != 0)
password.RemoveAt(password.Length - 1);
}
else password.AppendChar(cki.KeyChar);
}
return password;
}
示例4: PasswordMatcher
public PasswordMatcher(byte[] hash, SecureString matchPattern, byte[] salt, int iterations, bool leaveOpen)
{
_hash = hash;
int length = matchPattern.Length;
char[] chars = new char[length];
IntPtr pointer = IntPtr.Zero;
try
{
pointer = Marshal.SecureStringToBSTR(matchPattern);
Marshal.Copy(pointer, chars, 0, length);
}
finally
{
if (pointer != IntPtr.Zero)
{
Marshal.ZeroFreeBSTR(pointer);
}
if (!leaveOpen)
{
matchPattern.Dispose();
}
}
Buffer.BlockCopy(chars, 0, _matchPattern, 0, chars.Length);
for (int i = 0; i < chars.Length; i++)
{
chars[i] = '0';
}
_salt = salt;
_iterations = iterations;
LeaveOpen = leaveOpen;
}
示例5: Classes
/// <summary>
/// Create a new instance of Class for sending property
/// </summary>
/// <param name="NewMailMessage">Message to be sent</param>
/// <param name="Password">Secure String to keep Password confidential</param>
public Classes(MailMessage NewMailMessage, SecureString password)
{
Message.To.Add(NewMailMessage.To.ToString());
if (NewMailMessage.CC.Count != 0)
Message.CC.Add(NewMailMessage.CC.ToString());
Message.Subject = NewMailMessage.Subject;
Message.IsBodyHtml = NewMailMessage.IsBodyHtml;
Message.Body = NewMailMessage.Body;
Message.BodyEncoding = NewMailMessage.BodyEncoding;
Password = password;
password.Dispose();
}
示例6: ToSecureString
/// <summary>
/// Transforms a string into a SecureString.
/// </summary>
/// <param name = "value">
/// The string to transform.
/// </param>
/// <returns>
/// A secure string representing the contents of the original string.
/// </returns>
internal static SecureString ToSecureString(this string value)
{
if (value == null)
{
return null;
}
var rv = new SecureString();
try
{
foreach (char c in value)
{
rv.AppendChar(c);
}
return rv;
}
catch (Exception)
{
rv.Dispose();
throw;
}
}
示例7: DefaultConstructor
public void DefaultConstructor ()
{
try {
SecureString ss = new SecureString ();
Assert.IsFalse (ss.IsReadOnly (), "IsReadOnly");
Assert.AreEqual (0, ss.Length, "0");
ss.AppendChar ('a');
Assert.AreEqual (1, ss.Length, "1");
ss.Clear ();
Assert.AreEqual (0, ss.Length, "0b");
ss.InsertAt (0, 'b');
Assert.AreEqual (1, ss.Length, "1b");
ss.SetAt (0, 'c');
Assert.AreEqual (1, ss.Length, "1c");
Assert.AreEqual ("System.Security.SecureString", ss.ToString (), "ToString");
ss.RemoveAt (0);
Assert.AreEqual (0, ss.Length, "0c");
ss.Dispose ();
}
catch (NotSupportedException) {
Assert.Ignore (NotSupported);
}
}
示例8: remote_event_log_exists
private static bool remote_event_log_exists(string log, string remote_machine_name, string remote_domain_name, string remote_user_name, string remote_password_name) {
try {
SecureString pwd = new SecureString();
foreach (char c in remote_password_name)
pwd.AppendChar(c);
EventLogSession session = remote_machine_name.Trim() != ""
? new EventLogSession(remote_machine_name, remote_domain_name, remote_user_name, pwd, SessionAuthentication.Default)
: null;
pwd.Dispose();
EventLogQuery query = new EventLogQuery(log, PathType.LogName);
if (session != null)
query.Session = session;
EventLogReader reader = new EventLogReader(query);
if (reader.ReadEvent(TimeSpan.FromMilliseconds(500)) != null)
return true;
} catch(Exception e) {
logger.Error("can't login " + e.Message);
}
return false;
}
示例9: read_single_log_thread
private void read_single_log_thread(log_info log) {
string query_string = "*";
if (provider_name != "")
query_string = "*[System/Provider/@Name=\"" + provider_name + "\"]";
int max_event_count = int.MaxValue;
// debugging - load much less, faster testing
if (util.is_debug)
max_event_count = 250;
try {
// we can read the number of entres only for local logs
if (provider_name == "" && log.remote_machine_name == "") {
var dummy_log = new EventLog(log.log_type);
lock(this)
log.full_log_count_ = dummy_log.Entries.Count;
dummy_log.Dispose();
}
// waiting for user to set the password
if ( log.remote_machine_name != "")
while ( remote_password_ == "")
Thread.Sleep(100);
SecureString pwd = new SecureString();
foreach ( char c in remote_password_)
pwd.AppendChar(c);
EventLogSession session = log.remote_machine_name != "" ? new EventLogSession(log.remote_machine_name, remote_domain_name, remote_user_name, pwd, SessionAuthentication.Default) : null;
pwd.Dispose();
EventLogQuery query = new EventLogQuery(log.log_type, PathType.LogName, query_string);
query.ReverseDirection = reverse_;
if ( session != null)
query.Session = session;
EventLogReader reader = new EventLogReader(query);
int read_idx = 0;
for (EventRecord rec = reader.ReadEvent(); rec != null && !log.disposed_ && read_idx++ < max_event_count ; rec = reader.ReadEvent())
lock (this) {
log.last_events_.Add(rec);
++log.cur_log_count_;
}
lock (this)
log.listening_for_new_events_ = true;
// at this point, listen for new events
if (reverse_) {
// if reverse, I need to create another query, or it won't allow watching
query = new EventLogQuery(log.log_type, PathType.LogName, query_string);
if ( session != null)
query.Session = session;
}
using (var watcher = new EventLogWatcher(query))
{
watcher.EventRecordWritten += (o, e) => {
lock(this)
log.new_events_.Add(e.EventRecord);
};
watcher.Enabled = true;
while ( !log.disposed_)
Thread.Sleep(100);
}
} catch (Exception e) {
logger.Error("can't create event log " + log.log_type + "/" + remote_machine_name + " : " + e.Message);
errors_.add("Can't create Log " + log.log_type + " on machine " + remote_machine_name + ", Reason=" + e.Message);
}
}
示例10: TriggerRequestViewByUrl
/// <summary>
/// A method is used to send a WOPI view request to the WOPI server and get a html response.
/// </summary>
/// <param name="requestViewResourceUrl">A parameter represents the request URL for viewing a resource by using WOPI mode.</param>
/// <param name="userName">A parameter represents the name of user whose associated token will be return in the HTML content.</param>
/// <param name="password">A parameter represents the password of the user.</param>
/// <param name="domain">A parameter represents the domain of the user.</param>
/// <returns>A return value represents the html response from the WOPI server.</returns>
protected string TriggerRequestViewByUrl(string requestViewResourceUrl, string userName, string password, string domain)
{
if (string.IsNullOrEmpty(requestViewResourceUrl))
{
throw new ArgumentException("requestViewFileUri");
}
// Secure string only support 65536 length.
if (password.Length > 65536)
{
throw new ArgumentException("The Password length is larger than 65536, the test suite only support password less than 65536.");
}
string htmlContent = string.Empty;
// Create the HTTP request with browser's setting.
Uri requestTargetLocation = new Uri(requestViewResourceUrl);
HttpWebRequest request = HttpWebRequest.Create(requestTargetLocation) as HttpWebRequest;
request.Method = "GET";
request.UserAgent = @"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";
SecureString securePassword = new SecureString();
foreach (char passwordCharItem in password)
{
securePassword.AppendChar(passwordCharItem);
}
NetworkCredential credentialInstance = new NetworkCredential(userName, securePassword, domain);
securePassword.Dispose();
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(requestTargetLocation, "NTLM", credentialInstance);
request.Credentials = credentialCache;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
htmlContent = this.ReadHtmlContentFromResponse(response);
}
return htmlContent;
}
示例11: SecureStringUsingExample
// secure string for passwords or secret string data
public static void SecureStringUsingExample()
{
using (SecureString securePassword = new SecureString())
{
// getting
while (true)
{
ConsoleKeyInfo cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (cki.Key == ConsoleKey.Backspace)
{
if (securePassword.Length > 0)
{
securePassword.RemoveAt(securePassword.Length - 1);
Console.Write("-");
}
continue;
}
securePassword.AppendChar(cki.KeyChar);
Console.Write("*");
}
// showing
unsafe
{
char* buffer = null;
try
{
// decrypting
buffer = (char*)Marshal.SecureStringToCoTaskMemUnicode(securePassword);
for (var i = 0; buffer[i] != 0; i++)
Console.Write(buffer[i]);
}
finally
{
// buffer clearing
if (buffer != null) Marshal.ZeroFreeCoTaskMemUnicode((IntPtr)buffer);
}
}
securePassword.Dispose(); // not necessary in using construction
}
}
示例12: PBKDF2Password
/// <summary>
/// Makes a Password from a SecureString
/// </summary>
/// <param name="passwordString">The SecureString representing a password.</param>
/// <param name="leaveOpen">If no, the SecureString will be disposed after use.</param>
public PBKDF2Password(SecureString passwordString, bool leaveOpen)
{
int length = passwordString.Length;
char[] chars = new char[length];
IntPtr pointer = IntPtr.Zero;
try
{
pointer = Marshal.SecureStringToBSTR(passwordString);
Marshal.Copy(pointer, chars, 0, length);
}
finally
{
if (pointer != IntPtr.Zero)
{
Marshal.ZeroFreeBSTR(pointer);
}
if (!leaveOpen)
{
passwordString.Dispose();
}
}
byte[] bytes = new byte[chars.Length];
Buffer.BlockCopy(chars, 0, bytes, 0, bytes.Length);
for(int i = 0; i < chars.Length; i++)
{
chars[i] = '0';
}
setIterations();
this.gen(bytes, false);
}
示例13: UnsafeConstructor
public unsafe void UnsafeConstructor ()
{
try {
SecureString ss = null;
char[] data = new char[] { 'a', 'b', 'c' };
fixed (char* p = &data[0]) {
ss = new SecureString (p, data.Length);
}
Assert.IsFalse (ss.IsReadOnly (), "IsReadOnly");
Assert.AreEqual (3, ss.Length, "3");
ss.AppendChar ('a');
Assert.AreEqual (4, ss.Length, "4");
ss.Clear ();
Assert.AreEqual (0, ss.Length, "0b");
ss.InsertAt (0, 'b');
Assert.AreEqual (1, ss.Length, "1b");
ss.SetAt (0, 'c');
Assert.AreEqual (1, ss.Length, "1c");
ss.RemoveAt (0);
Assert.AreEqual (0, ss.Length, "0c");
ss.Dispose ();
}
catch (NotSupportedException) {
Assert.Ignore (NotSupported);
}
}
示例14: GetDisposed
private SecureString GetDisposed ()
{
SecureString ss = new SecureString ();
ss.Dispose ();
return ss;
}
示例15: EventLogInput
public EventLogInput(InputElement input, SelectorElement selector, EventQueue equeue)
: base(input, selector, equeue)
{
// Event log query with suppressed events logged by this service
StringBuilder qstr = new StringBuilder();
qstr.Append("<QueryList>");
qstr.Append("<Query>");
qstr.Append(selector.Query.Value);
qstr.Append("<Suppress Path=\"Application\">*[System/Provider/@Name=\"F2B\"]</Suppress>");
qstr.Append("</Query>");
qstr.Append("</QueryList>");
EventLogSession session = null;
if (input.Server != string.Empty)
{
SecureString pw = new SecureString();
Array.ForEach(input.Password.ToCharArray(), pw.AppendChar);
session = new EventLogSession(input.Server, input.Domain,
input.Username, pw,
SessionAuthentication.Default);
pw.Dispose();
}
EventLogQuery query = new EventLogQuery(null, PathType.LogName, qstr.ToString());
if (session != null)
{
query.Session = session;
}
// create event watcher (must be enable later)
watcher = new EventLogWatcher(query);
watcher.EventRecordWritten +=
new EventHandler<EventRecordWrittenEventArgs>(
(s, a) => EventRead(s, a));
// event data parsers (e.g. XPath + regex to extract event data)
// (it is important to preserve order - it is later used as array index)
List<Tuple<string, EventDataElement>> tmp = new List<Tuple<string, EventDataElement>>();
tmp.Add(new Tuple<string,EventDataElement>("address", selector.Address));
tmp.Add(new Tuple<string,EventDataElement>("port", selector.Port));
tmp.Add(new Tuple<string,EventDataElement>("username", selector.Username));
tmp.Add(new Tuple<string,EventDataElement>("domain", selector.Domain));
evtmap = new Dictionary<string, Tuple<int, int>>();
evtregex = new List<Regex>();
List<string> xPathRefs = new List<string>();
for (int i = 0; i < tmp.Count; i++)
{
string evtdescr = tmp[i].Item1;
EventDataElement evtdata = tmp[i].Item2;
if (evtdata == null || string.IsNullOrEmpty(evtdata.XPath))
{
if (evtdescr == "address")
{
throw new ArgumentException("No address in " + Name + " configuration");
}
evtmap[evtdescr] = new Tuple<int, int>(i, -1);
continue;
}
Regex regex = null;
if (!string.IsNullOrWhiteSpace(evtdata.Value))
{
string evtstr = evtdata.Value.Trim();
try
{
regex = new Regex(evtstr, RegexOptions.IgnoreCase | RegexOptions.Singleline);
}
catch (ArgumentException ex)
{
Log.Error("Invalid " + Name + " " + evtdescr + " regex: "
+ evtstr + " (" + ex.Message + ")");
throw;
}
}
evtregex.Add(regex);
if (xPathRefs.Contains(evtdata.XPath))
{
int index = xPathRefs.IndexOf(evtdata.XPath);
evtmap[evtdescr] = new Tuple<int, int>(i, index);
}
else
{
xPathRefs.Add(evtdata.XPath);
evtmap[evtdescr] = new Tuple<int, int>(i, xPathRefs.Count - 1);
}
}
Debug.Assert(tmp.Count == evtmap.Count,
"Invalid index map size (tmp[" + tmp.Count
+ "] != map[" + evtmap.Count + "]).");
evtsel = new EventLogPropertySelector(xPathRefs);
}