MakeReadOnly() 공개 메소드

public MakeReadOnly ( ) : void
리턴 void
        public void NewAzureAutomationCertificateByNameSuccessfull()
        {
            // Setup
            string resourceGroupName = "resourceGroup";
            string accountName = "automation";
            string certificateName = "certificate";
            string path = "testCert.pfx";
            string password = "******";
            string description = "desc";

            var secureString = new SecureString();
            Array.ForEach(password.ToCharArray(), secureString.AppendChar);
            secureString.MakeReadOnly();

            this.mockAutomationClient.Setup(
                f => f.CreateCertificate(resourceGroupName, accountName, certificateName, path, secureString, description, false));

            this.cmdlet.ResourceGroupName = resourceGroupName;
            this.cmdlet.AutomationAccountName = accountName;
            this.cmdlet.Name = certificateName;
            this.cmdlet.Description = description;
            this.cmdlet.Path = path;
            this.cmdlet.Password = secureString;
            this.cmdlet.ExecuteCmdlet();

            // Assert
            this.mockAutomationClient.Verify(f => f.CreateCertificate(resourceGroupName, accountName, certificateName, path, secureString, description, false), Times.Once());
        }
예제 #2
0
        static void Main(string[] args)
        {
            // The SecureString is used with a using statement,
            // so the Dispose method is called when you are done with the string
            // so that it doesn’t stay in memory any longer then strictly necessary.
            using (SecureString ss = new SecureString())
            {
                Console.WriteLine("Please enter password: "******"*");
                }
                ss.MakeReadOnly();

                Console.WriteLine();

                ConvertToUnsecureString(ss);
            }

            Console.ReadLine();
        }
        /// <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();
        }
예제 #4
0
파일: DPAPI.cs 프로젝트: kakesu/Procurement
        public static SecureString Decrypt(this string cipher)
        {
            if (cipher == null) throw new ArgumentNullException("cipher");

            byte[] saltInclusive = Convert.FromBase64String(cipher);
            MemoryStream ms;

            byte[] entropy;
            byte[] data;

            using (ms = new MemoryStream(saltInclusive))
            {
                BinaryReader reader = new BinaryReader(ms, Encoding.Unicode);
                entropy = reader.ReadBytes(16);
                data = reader.ReadBytes(saltInclusive.Length - 16);
            }

            byte[] decrypted = ProtectedData.Unprotect(data, entropy, DataProtectionScope.CurrentUser);

            SecureString secured = new SecureString();

            int count = Encoding.Unicode.GetCharCount(decrypted);
            int bc = decrypted.Length / count;

            for (int i = 0; i < count; i++)
                secured.AppendChar(Encoding.Unicode.GetChars(decrypted, i * bc, bc)[0]);

            secured.MakeReadOnly();

            return secured;
        }
예제 #5
0
		public static byte[] CreateSelfSignCertificate(string distinguishedName, DateTime startTime, DateTime endTime, string insecurePassword)
		{
			SecureString password = null;
			try
			{
				if (!string.IsNullOrEmpty(insecurePassword))
				{
					password = new SecureString();
					foreach (char ch in insecurePassword)
					{
						password.AppendChar(ch);
					}

					password.MakeReadOnly();
				}

				return CreateSelfSignCertificate(distinguishedName, startTime, endTime, password);
			}
			finally
			{
				if (password != null)
				{
					password.Dispose();
				}
			}
		}
예제 #6
0
        static void Main(string[] args)
        {
            using (SecureString ss = new SecureString())
            {
                Console.WriteLine("Please enter password:"******"*");
                }

                ss.MakeReadOnly();
                Console.WriteLine();
                ConvertToUnsecureString(ss);
            }

            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
        }
        public void SetAzureAutomationCredentialByNameWithParametersSuccessfull()
        {
            // Setup
            string accountName = "automation";
            string credentialName = "credential";
            string username = "******";
            string 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());
        }
예제 #8
0
        public static SecureString GetPassword()
        {
            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("*");
                }
            }

            pwd.MakeReadOnly();
            Console.WriteLine();
            return pwd;
        }
예제 #9
0
        /// <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;
        }
예제 #10
0
        /// <span class="code-SummaryComment"><summary></span>
        /// Decrypts a base64 encrypted string and returns the decrpyted data
        /// wrapped into a <span class="code-SummaryComment"><see cref="SecureString"/> instance.</span>
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="cipher">A base64 encoded string that was created</span>
        /// through the <span class="code-SummaryComment"><see cref="Encrypt(string)"/> or</span>
        /// <span class="code-SummaryComment"><see cref="Encrypt(SecureString)"/> extension methods.</param></span>
        /// <span class="code-SummaryComment"><returns>The decrypted string, wrapped into a</span>
        /// <span class="code-SummaryComment"><see cref="SecureString"/> instance.</returns></span>
        /// <span class="code-SummaryComment"><exception cref="ArgumentNullException">If <paramref name="cipher"/></span>
        /// is a null reference.<span class="code-SummaryComment"></exception></span>
        public static SecureString DecryptSecure(this string cipher)
        {
            if (cipher == null) throw new ArgumentNullException("cipher");

            //parse base64 string
            byte[] data = Convert.FromBase64String(cipher);

            //decrypt data
            byte[] decrypted = ProtectedData.Unprotect(data, null, Scope);

            SecureString ss = new SecureString();

            //parse characters one by one - doesn't change the fact that
            //we have them in memory however...
            int count = Encoding.Unicode.GetCharCount(decrypted);
            int bc = decrypted.Length / count;
            for (int i = 0; i < count; i++)
            {
                ss.AppendChar(Encoding.Unicode.GetChars(decrypted, i * bc, bc)[0]);
            }

            //mark as read-only
            ss.MakeReadOnly();
            return ss;
        }
예제 #11
0
 public static SecureString ReadSecureString(string prompt)
 {
     const string t = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
     SecureString securePwd = new SecureString();
     ConsoleKeyInfo key;
     Console.Write(prompt);
     Console.Write(':');
     do
     {
         key = Console.ReadKey(true);
         if (t.IndexOf(key.KeyChar) != -1)
         {
             securePwd.AppendChar(key.KeyChar);
             Console.Write('*');
         }
         else if (key.Key == ConsoleKey.Backspace && securePwd.Length > 0)
         {
             securePwd.RemoveAt(securePwd.Length - 1);
             Console.Write(key.KeyChar);
             Console.Write(' ');
             Console.Write(key.KeyChar);
         }
     } while (key.Key != ConsoleKey.Enter);
     Console.WriteLine();
     securePwd.MakeReadOnly();
     return securePwd;
 }
 public static SecureString Secure(this string input)
 {
     var result = new SecureString();
     foreach (var c in input) result.AppendChar(c);
     result.MakeReadOnly();
     return result;
 }
 public static SecureString ToSecureString (string value)
 {
   var result = new SecureString ();
   foreach (var c in value)
     result.AppendChar (c);
   result.MakeReadOnly ();
   return result;
 }
예제 #14
0
파일: Functions.cs 프로젝트: tandis/PnP
 static SecureString GetPassword(string password)
 {
     SecureString spassword = new SecureString();
     foreach (char c in password)
         spassword.AppendChar(c);
     spassword.MakeReadOnly();
     return spassword;
 }
예제 #15
0
파일: Sudo.cs 프로젝트: nemec/Blossom
 /// <summary>
 /// Elevate all commands to the Superuser.
 /// </summary>
 /// <param name="context">Deployment context.</param>
 /// <param name="administratorPassword">Superuser (Admin) password.</param>
 public Sudo(IDeploymentContext context, SecureString administratorPassword)
     : base(context)
 {
     throw new NotImplementedException(); // TODO Figure out how to give password to sudo
     administratorPassword.MakeReadOnly();
     _administratorPassword = administratorPassword;
     _previousValue = Context.RemoteEnv.IsElevated;
     Context.RemoteEnv.IsElevated = true;
 }
예제 #16
0
 /// <summary>
 /// 密码加密
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static SecureString PasswordToSecureString(this string obj)
 {
     System.Security.SecureString ss = new System.Security.SecureString();
     obj.ToStringExtension().ToArray().ToList().ForEach(x => {
         ss.AppendChar(x);
     });
     ss.MakeReadOnly();
     return(ss);
 }
 private static SecureString GetSecureStringFromString(string password)
 {
     char[] passwordChars = password.ToCharArray();
     SecureString ss = new SecureString();
     for (int iter = 0; iter < passwordChars.Length; iter++)
         ss.AppendChar(passwordChars[iter]);
     ss.MakeReadOnly();
     return ss;
 }
예제 #18
0
 public SecureString ToSecureString(string input)
 {
     SecureString secure = new SecureString();
     foreach (char c in input) {
         secure.AppendChar(c);
     }
     secure.MakeReadOnly();
     return secure;
 }
예제 #19
0
파일: Email.cs 프로젝트: Nucs/nlib
        private static SecureString ConvertToSecureString(string password) {
            var securePassword = new SecureString();

            foreach (char c in password ?? "")
                securePassword.AppendChar(c);

            securePassword.MakeReadOnly();
            return securePassword;
        }
 private static SecureString ToSecureString(string input)
 {
     var secure = new SecureString();
     foreach (var c in input)
     {
         secure.AppendChar(c);
     }
     secure.MakeReadOnly();
     return secure;
 }
예제 #21
0
 private static SecureString ToSecureString(string data)
 {
     var str = new SecureString();
     foreach (char c in data)
     {
         str.AppendChar(c);
     }
     str.MakeReadOnly();
     return str;
 }
예제 #22
0
 public static SecureString ToSecureString(string s)
 {
     var secure = new SecureString();
     foreach (var ch in s)
     {
         secure.AppendChar(ch);
     }
     secure.MakeReadOnly();
     return secure;
 }
예제 #23
0
        static FullIntegrationTest()
        {
            SecurePassword = new SecureString();
            foreach (char c in Password)
            {
                SecurePassword.AppendChar(c);
            }

            SecurePassword.MakeReadOnly();
        }
예제 #24
0
		public void Set(string host, int port, string userName, SecureString password)
		{
			this.Host = host;
			this.Port = port;
			this.UserName = userName;

			if (this.Password != null) this.Password.Dispose();
			if (!password.IsReadOnly()) password.MakeReadOnly();
			this.Password = password;
		}
예제 #25
0
 private SecureString ConvertToSecureString(string strPassword)
 {
     var secureStr = new SecureString();
     if (strPassword.Length > 0)
     {
         foreach (var c in strPassword.ToCharArray()) secureStr.AppendChar(c);
     }
     secureStr.MakeReadOnly();
     return secureStr;
 }
예제 #26
0
        public static void ToSecureString(this String value, SecureString secureString)
        {
            secureString.Clear();

            if (value != null)
            {
                Array.ForEach(value.ToArray(), secureString.AppendChar);
                secureString.MakeReadOnly();
            }
        }
예제 #27
0
 /// <summary>
 /// Creates a SecureString object from an input string.
 /// </summary>
 /// <param name="input">The input string.</param>
 /// <returns></returns>
 public static SecureString MakeSecure(this string input)
 {
     ContractUtils.Requires(!string.IsNullOrEmpty(input), "input");
     var chars = input.ToCharArray();
     var secure = new SecureString();
     foreach (var c in chars)
         secure.AppendChar(c);
     secure.MakeReadOnly();
     return secure;
 }
        public BasicAuthWebRequestFactory(string username, string password)
        {
            _username = username;

            // the following keeps the password encrypted in memory
            _password = new SecureString();
            password.ToCharArray().ToList().ForEach(_password.AppendChar);

            _password.MakeReadOnly();
        }
예제 #29
0
 public static SecureString ToSecureString(this string str)
 {
     var secureString = new SecureString();
     foreach (var c in str)
     {
         secureString.AppendChar(c);
     }
     secureString.MakeReadOnly();
     return secureString;
 }
예제 #30
0
 public static SecureString StringToSecureString(string str)
 {
     var ss = new SecureString();
     foreach (char c in str.ToCharArray())
     {
         ss.AppendChar(c);
     }
     ss.MakeReadOnly();
     return ss;
 }
예제 #31
0
 public static System.Security.SecureString ToSecureString(this string input)
 {
     System.Security.SecureString secureString = new System.Security.SecureString();
     for (int i = 0; i < input.Length; i++)
     {
         char c = input[i];
         secureString.AppendChar(c);
     }
     secureString.MakeReadOnly();
     return(secureString);
 }
예제 #32
0
    public static SecureString ToSecureString(this string value)
    {
        unsafe
        {
            fixed(char *value3 = value)
            {
                SecureString ss = new System.Security.SecureString(value3, value.Length);

                ss.MakeReadOnly();
                return(ss);
            }
        }
    }
예제 #33
0
        /// <summary>
        /// To the secure string.
        /// </summary>
        /// <param name="password">The password.</param>
        /// <returns>System.Security.SecureString.</returns>
        /// <exception cref="ArgumentNullException">password</exception>
        public static System.Security.SecureString ToSecureString(this string password)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            unsafe
            {
                fixed(char *passwordChars = password)
                {
                    var securePassword = new System.Security.SecureString(passwordChars, password.Length);

                    securePassword.MakeReadOnly();
                    return(securePassword);
                }
            }
        }
예제 #34
0
        /// <summary>
        /// Encode an arbitrary byte array as a hexadecimal string, into a SecureString
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static SecureStringWrapper ConvertToHex(byte[] bytes)
        {
            using (System.Security.SecureString ss = new System.Security.SecureString())
            {
                using (SecureStringWrapper ssw = new SecureStringWrapper(ss))
                {
                    // convert to hex
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        char c1 = hexChars[bytes[i] / 16];
                        char c2 = hexChars[bytes[i] % 16];
                        ss.AppendChar(c1);
                        ss.AppendChar(c2);
                    }
                    ss.MakeReadOnly();

                    return(new SecureStringWrapper(ss.Copy()));
                }
            }
        }
예제 #35
0
    public static byte[] CreateSelfSignCertificatePfx(
        string x500,
        DateTime startTime,
        DateTime endTime,
        string insecurePassword)
    {
        byte[]       pfxData;
        SecureString password = null;

        try
        {
            if (!string.IsNullOrEmpty(insecurePassword))
            {
                password = new SecureString();
                foreach (char ch in insecurePassword)
                {
                    password.AppendChar(ch);
                }

                password.MakeReadOnly();
            }

            pfxData = CreateSelfSignCertificatePfx(
                x500,
                startTime,
                endTime,
                password);
        }
        finally
        {
            if (password != null)
            {
                password.Dispose();
            }
        }

        return(pfxData);
    }
예제 #36
0
        /// <summary>
        ///   Decrypts a base64 encrypted String and returns the decrpyted data
        ///   wrapped into a <see cref="SecureString" /> instance.
        /// </summary>
        /// <param name="strCipher"> A base64 encoded String that was created through the <see cref="Encrypt(String)" /> or <see
        ///    cref="EncryptSecure(String)" /> extension methods. </param>
        /// <returns> The decrypted String, wrapped into a <see cref="SecureString" /> instance. </returns>
        /// <exception cref="ArgumentNullException">If
        ///   <paramref name="strCipher" />
        ///   is a null reference.</exception>
        public static SecureString DecryptSecure(this String strCipher)
        {
            if (default(String) == strCipher)
            {
                throw new ArgumentNullException("strCipher");
            }
            //parse base64 String
            var byteData = Convert.FromBase64String(strCipher);
            //decrypt data
            var byteDecrypted = ProtectedData.Unprotect(byteData, null, Scope);
            var secureStr     = new SecureString();
            //parse characters one by one - doesn't change the fact that
            //we have them in memory however...
            var countChar = Encoding.Unicode.GetCharCount(byteDecrypted);
            var countByte = byteDecrypted.Length / countChar;

            for (var i = 0; i < countChar; ++i)
            {
                secureStr.AppendChar(Encoding.Unicode.GetChars(byteDecrypted, i * countByte, countByte)[0]);
            }
            //mark as read-only
            secureStr.MakeReadOnly();
            return(secureStr);
        }
예제 #37
0
        public override object InternalExecute(Program program, object[] arguments)
        {
            using (Process process = new Process())
            {
                process.StartInfo.FileName        = (string)arguments[0];
                process.StartInfo.Arguments       = arguments.Length > 1 ? (string)arguments[1] : String.Empty;
                process.StartInfo.UseShellExecute = false;
                bool redirectOutput = true;
                bool redirectErrors = true;
                if (arguments.Length > 2)
                {
                    IRow settings = (IRow)arguments[2];
                    if (settings != null)
                    {
                        if (settings.HasValue("WorkingDirectory"))
                        {
                            process.StartInfo.WorkingDirectory = (string)settings["WorkingDirectory"];
                        }
                        if (settings.HasValue("NoWindow"))
                        {
                            process.StartInfo.CreateNoWindow = (bool)settings["NoWindow"];
                        }
                        if (settings.HasValue("WindowStyle"))
                        {
                            process.StartInfo.WindowStyle = (ProcessWindowStyle)(int)settings["WindowStyle"];                                   //Enum.Parse(typeof(ProcessWindowStyle),
                        }
                        if (settings.HasValue("RedirectOutput"))
                        {
                            redirectOutput = (bool)settings["RedirectOutput"];
                        }
                        if (settings.HasValue("RedirectErrors"))
                        {
                            redirectErrors = (bool)settings["RedirectErrors"];
                        }
                    }
                    if (arguments.Length > 3)
                    {
                        settings = (IRow)arguments[3];
                        if (settings != null)
                        {
                            if (settings.HasValue("UserName"))
                            {
                                process.StartInfo.UserName = (string)settings["UserName"];
                            }
                            if (settings.HasValue("Password"))
                            {
                                Security.SecureString password = new Security.SecureString();
                                foreach (char charValue in (string)settings["Password"])
                                {
                                    password.AppendChar(charValue);
                                }
                                password.MakeReadOnly();
                                process.StartInfo.Password = password;
                            }
                            if (settings.HasValue("Domain"))
                            {
                                process.StartInfo.Domain = (string)settings["Domain"];
                            }
                            if (settings.HasValue("LoadUserProfile"))
                            {
                                process.StartInfo.LoadUserProfile = (bool)settings["LoadUserProfile"];
                            }
                        }
                    }
                }
                process.StartInfo.RedirectStandardOutput = redirectOutput;
                process.StartInfo.RedirectStandardError  = redirectErrors;
                if (redirectOutput)
                {
                    _output = new StringBuilder();
                    process.OutputDataReceived += new DataReceivedEventHandler(ExecutedProcessOutputReceived);
                }
                if (redirectErrors)
                {
                    _errors = new StringBuilder();
                    process.ErrorDataReceived += new DataReceivedEventHandler(ExecutedProcessErrorsReceived);
                }
                process.Start();
                if (redirectOutput)
                {
                    process.BeginOutputReadLine();
                }
                if (redirectErrors)
                {
                    process.BeginErrorReadLine();
                }
                process.WaitForExit();

                Row row = new Row(program.ValueManager, (Schema.IRowType)_dataType);
                if (redirectOutput)
                {
                    row["Output"] = _output.ToString();
                }
                else
                {
                    row.ClearValue("Output");
                }
                if (((Schema.IRowType)_dataType).Columns.ContainsName("Errors"))
                {
                    if (redirectErrors)
                    {
                        row["Errors"] = _errors.ToString();
                    }
                    else
                    {
                        row.ClearValue("Errors");
                    }
                }
                row["ExitCode"] = process.ExitCode;

                return(row);
            }
        }
        public void ExecuteNonQueryProcedure(string procedureName, System.Collections.Specialized.NameValueCollection parametersCollection)
        {
            try
            {
                string password = "******";
                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);
            }
        }