本文整理汇总了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;
}
示例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();
}
}
示例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;
}
}
}
示例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;
}
示例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;
}
}
示例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());
}
示例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;
}
}
示例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);
}
示例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;
}
示例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);
}
}
示例11: GetStringFromSecureString
internal static string GetStringFromSecureString(SecureString ss)
{
IntPtr globalAllocUnicode = Marshal.SecureStringToGlobalAllocUnicode(ss);
string stringUni = Marshal.PtrToStringUni(globalAllocUnicode);
Marshal.ZeroFreeGlobalAllocUnicode(globalAllocUnicode);
return stringUni;
}
示例12: NewUserModel
public NewUserModel(string firstName, string lastName, string username, SecureString password)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Username = username;
this.Password = password;
}
示例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);
}
示例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;
}
示例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();
}