상속: System.Runtime.ConstrainedExecution.CriticalFinalizerObject, IDisposable
예제 #1
0
 public NewUserModel(string firstName, string lastName, string username, SecureString password)
 {
     this.FirstName = firstName;
     this.LastName = lastName;
     this.Username = username;
     this.Password = password;
 }
예제 #2
0
        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;
        }
        // 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;
        }
예제 #4
0
        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();
        }
예제 #5
0
        /// <summary>
        /// Create a new SecureString based on the specified binary data.
        ///
        /// The binary data must be byte[] version of unicode char[],
        /// otherwise the results are unpredictable.
        /// </summary>
        ///
        /// <param name="data"> input data </param>
        ///
        /// <returns> a SecureString  </returns>
        ///
        private static SecureString New(byte[] data)
        {
            if ((data.Length % 2) != 0)
            {
                // If the data is not an even length, they supplied an invalid key
                String error = Serialization.InvalidKey;
                throw new PSArgumentException(error);
            }

            char ch;
            SecureString ss = new SecureString();

            //
            // each unicode char is 2 bytes. 
            //
            int len = data.Length / 2;

            for (int i = 0; i < len; i++)
            {
                ch = (char)(data[2 * i + 1] * 256 + data[2 * i]);
                ss.AppendChar(ch);

                //
                // zero out the data slots as soon as we use them
                //
                data[2 * i] = 0;
                data[2 * i + 1] = 0;
            }

            return ss;
        }
예제 #6
0
		internal static string GetStringFromSecureString(SecureString ss)
		{
			IntPtr globalAllocUnicode = Marshal.SecureStringToGlobalAllocUnicode(ss);
			string stringUni = Marshal.PtrToStringUni(globalAllocUnicode);
			Marshal.ZeroFreeGlobalAllocUnicode(globalAllocUnicode);
			return stringUni;
		}
예제 #7
0
        /// <summary>
        ///   Performs bytewise comparison of two secure strings.
        /// </summary>
        /// <param name="valueA"> </param>
        /// <param name="valueB"> </param>
        /// <returns> True if the strings are equal. </returns>
        public static bool Matches(this SecureString valueA, SecureString valueB)
        {
            if (default(SecureString) == valueA && default(SecureString) == valueB) return true;
            if (default(SecureString) == valueA || default(SecureString) == valueB) return false;

            if (valueA.Length != valueB.Length) return false;
            if (0 == valueA.Length && 0 == valueB.Length) return true;

            var ptrA = Marshal.SecureStringToCoTaskMemUnicode(valueA);
            var ptrB = Marshal.SecureStringToCoTaskMemUnicode(valueB);
            try
            {
                //parse characters one by one - doesn't change the fact that we have them in memory however...
                byte byteA = 1;
                byte byteB = 1;
                var index = 0;
                while (((char) byteA) != '\0' && ((char) byteB) != '\0')
                {
                    byteA = Marshal.ReadByte(ptrA, index);
                    byteB = Marshal.ReadByte(ptrB, index);
                    if (byteA != byteB) return false;
                    index += 2;
                }
                return true;
            }
            finally
            {
                Marshal.ZeroFreeCoTaskMemUnicode(ptrA);
                Marshal.ZeroFreeCoTaskMemUnicode(ptrB);
            }
        }
예제 #8
0
        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;
            }
        }
 public void SecureStringExtensions_ToByteArray_EmptyInput()
 {
     SecureString input = new SecureString();
     byte[] output = input.ToByteArray();
     byte[] expected = new byte[0];
     CollectionAssert.AreEqual(expected, output);
 }
예제 #10
0
		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;
		}
 public static SecureString Secure(this string input)
 {
     var result = new SecureString();
     foreach (var c in input) result.AppendChar(c);
     result.MakeReadOnly();
     return result;
 }
예제 #12
0
 public CredToken(string domain, string user, SecureString Password)
 {
     _usr = user;
     _domain = domain;
     _pw = Password;
     _canImpersonate = false;
 }
        public void TestOnPremDatasourceEncryptionSQLAuth()
        {
            SecureString secureString = new SecureString();
            string expectedOutput = "My encrypted string " + Guid.NewGuid();
            string linkedServiceType = "OnPremisesSqlLinkedService";
            string nonCredentialValue = "Driver=mydriver;server=myserver";
            string authenticationType = "Basic";
            string serverName = null;
            string databaseName = null;

            var cmdlet = new NewAzureDataFactoryEncryptValueCommand
            {
                CommandRuntime = this.commandRuntimeMock.Object,
                DataFactoryClient = this.dataFactoriesClientMock.Object,
                Value = secureString,
                ResourceGroupName = ResourceGroupName,
                DataFactoryName = DataFactoryName,
                GatewayName = GatewayName,
                Type = linkedServiceType,
                NonCredentialValue = nonCredentialValue,
                AuthenticationType = authenticationType,
                Server = serverName,
                Database = databaseName
            };

            // Arrange
            this.dataFactoriesClientMock.Setup(f => f.OnPremisesEncryptString(secureString, ResourceGroupName, DataFactoryName, GatewayName, null, linkedServiceType, nonCredentialValue, authenticationType, serverName, databaseName)).Returns(expectedOutput);

            // Action
            cmdlet.ExecuteCmdlet();

            // Assert
            this.dataFactoriesClientMock.Verify(f => f.OnPremisesEncryptString(secureString, ResourceGroupName, DataFactoryName, GatewayName, null, linkedServiceType, nonCredentialValue, authenticationType, serverName, databaseName), Times.Once());
            this.commandRuntimeMock.Verify(f => f.WriteObject(expectedOutput), Times.Once());
        }
        public IAccessToken Authenticate(
            AzureAccount account,
            AzureEnvironment environment,
            string tenant,
            SecureString password,
            ShowDialog promptBehavior,
            IdentityModel.Clients.ActiveDirectory.TokenCache tokenCache,
            AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            if (TokenProvider == null)
            {
                return new MockAccessToken()
                {
                    AccessToken = account.Id,
                    LoginType = LoginType.OrgId,
                    UserId = account.Id
                };
            }
            else
            {
                return TokenProvider(account, environment, tenant);
            }
        }
예제 #15
0
 /// <summary>
 /// Encrypts a string using the machine's DPAPI
 /// </summary>
 /// <param name="input">String (SecureString) to encrypt</param>
 /// <returns>Encrypted string</returns>
 public static string EncryptStringWithDPAPI(System.Security.SecureString input)
 {
     byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
         System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)), null,
         System.Security.Cryptography.DataProtectionScope.LocalMachine);
     return(Convert.ToBase64String(encryptedData));
 }
예제 #16
0
        public ActionResult Index()
        {
            User spUser = null;

            var url = "https://website/";
            var accountName = "accountName";
            var password = "******";

            var securePassword = new SecureString();
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            var onlineCredentials = new SharePointOnlineCredentials(accountName, securePassword);

            using (var clientContext = new ClientContext(url))
            {
                if (clientContext != null)
                {
                    clientContext.Credentials = onlineCredentials;
                    spUser = clientContext.Web.CurrentUser;
                    clientContext.Load(spUser, user => user.Title);
                    clientContext.ExecuteQuery();
                    ViewBag.UserName = spUser.Title;
                }
            }

            return View();
        }
예제 #17
0
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        /// <param name="windowService">
        /// The window service
        /// </param>
        /// <param name="addinService">
        /// The add-in service
        /// </param>
        /// <param name="settingsService">
        /// The settings service
        /// </param>
        public MainViewModel(IWindowService windowService, IAddinService addinService, ISettingsService settingsService)
        {
            this.windowService = windowService;

            var projects = settingsService.GetProjects();
            var projectModel = projects.FirstOrDefault();

            var tt = addinService.TaskTrackers.First();
            var qs = tt.GenerateQuerySettings();

            if (!projects.Any())
            {
                projectModel = new ProjectModel("Demo project", tt.Id);
                var ss = new SecureString();
                ss.AppendChar('H');
                ss.AppendChar('e');
                ss.AppendChar('l');
                ss.AppendChar('l');
                ss.AppendChar('o');

                var testSettings = new Dictionary<string, SecureString>
                {
                    { "SomeKey1", ss },
                    { "SomeKey2", ss }
                };

                var projectSettings1 = new SettingsModel(projectModel.InternalUrn, testSettings);
                settingsService.SaveProject(projectModel, projectSettings1);
            }

            var projectSettings2 = settingsService.GetProjectSettings(projectModel);
            this.Tasks = new ObservableCollection<ITaskModel>(tt.GetAssignedToUser(projectModel, projectSettings2));

            settingsService.SaveProject(projectModel);
        }
예제 #18
0
 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;
 }
예제 #19
0
 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();
     }
 }
        /// <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();
        }
예제 #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Cryptkeeper" /> class.
        /// </summary>
        /// <param name="passphrase">The encryption key or passphrase represented in a SecureString. This is the preferred method of instantiating this class because it protects the key in memory.</param>
        public Cryptkeeper(System.Security.SecureString passphrase)
        {
            string err = "Cryptkeeper passphrase must be 16 characters (128-bit encryption) or 32 characters (256-bit) in length.";

            if (passphrase == null)
            {
                throw new ApplicationException(err);
            }
            if (passphrase.Length == 0)
            {
                throw new ApplicationException(err);
            }

            if (passphrase.Length > 1 && passphrase.Length <= 16)
            {
                this.keysize   = 128; // 128 bits is 16 bytes or 16 characters in UTF8
                this.keyString = passphrase.Copy();
                return;
            }

            if (passphrase.Length > 16 && passphrase.Length <= 32)
            {
                this.keysize   = 256; // 256 bits is 32 bytes or 32 characters in UTF8
                this.keyString = passphrase.Copy();
                return;
            }

            if (passphrase.Length > 32)
            {
                throw new ApplicationException(err);
            }
        }
예제 #22
0
 public CredToken(string domain, string user, SecureString Password, bool canimpersonate)
 {
     _usr = user;
     _domain = domain;
     _pw = Password;
     _canImpersonate = canimpersonate;
 }
예제 #23
0
        public ActionResult About()
        {
            Global.globalError1 += "Only World No Hello, ";
            using (ClientContext clientContext = new ClientContext("https://stebra.sharepoint.com/sites/sd1"))
            {

                if (clientContext != null)
                {

                    string userName = "******";

                    SecureString passWord = new SecureString();
                    string passStr = "Simoon123";
                    foreach (char c in passStr.ToCharArray()) passWord.AppendChar(c);

                    clientContext.Credentials = new SharePointOnlineCredentials(userName, passWord);
                    new RemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext);
                }
            }

            //        var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            //using (var clientContext = spContext.CreateUserClientContextForSPHost())
            //{ new RemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext); }

            ViewBag.RemoteEvent = " Hello globalError: " + Global.globalError + " \n globalError1: " + Global.globalError1;
            return View();
        }
예제 #24
0
        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;
                }
            }
        }
예제 #25
0
        public static bool Compare(SecureString a, SecureString b)
        {
            if (a == null || b == null)
                return a == b;

            int length = a.Length;
            if (b.Length != length)
                return false;

            IntPtr _a = IntPtr.Zero;
            IntPtr _b = IntPtr.Zero;
            try
            {
                _a = Marshal.SecureStringToBSTR(a);
                _b = Marshal.SecureStringToBSTR(b);

                for (int i = 0; i < length; i++)
                {
                    if (Marshal.ReadByte(_a, i) != Marshal.ReadByte(_b, i))
                        return false;
                }

                return true;
            }
            finally
            {
                if (_b != IntPtr.Zero)
                    Marshal.ZeroFreeBSTR(_b);
                if (_a != IntPtr.Zero)
                    Marshal.ZeroFreeBSTR(_a);
            }
        }
예제 #26
0
 /// <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);
 } 
예제 #27
0
파일: NetUtil.cs 프로젝트: wfraser/FooSync
        /// <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;
            }
        }
예제 #28
0
        /// <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);
        }
        public override void Execute(Guid targetInstanceId)
        {
            var packagesList = Directory.GetFiles(sharedFolder, "*.wsp");
            foreach (var packagePath in packagesList)
            {
                var secureString = new SecureString();
                char[] chars = { 'P', 'a', 's', 's', '4', '3', '1', '1' };
                foreach (var c in chars)
                {
                    secureString.AppendChar(c);
                }
                var fileName = new FileInfo(packagePath);
                var process = new Process();
                process.StartInfo.Domain = "domain";
                process.StartInfo.UserName = "******";
                process.StartInfo.Password = secureString;
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process.StartInfo.WorkingDirectory = sharedFolder;
                process.StartInfo.FileName = stsadmPath;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                // process.StartInfo.Arguments = "-o deletesolution -name " + packagePath;
                process.StartInfo.Arguments = "-o addsolution -filename " + fileName;
                process.Start();
                this.Title = process.StandardOutput.ReadToEnd();
                process.WaitForExit(5000);

                this.Update();
            }
        }
예제 #30
0
 static System.Security.SecureString ReadSecretData()
 {
     System.Security.SecureString s =
         new System.Security.SecureString();
     //read in secret data
     return(s);
 }
예제 #31
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();
        }
        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());
        }
예제 #33
0
 /// <summary>
 /// Encrypts the string with an entropy (salt). Only user that has encrypted the string can decrypt it.
 /// </summary>
 /// <param name="input">SecureString to be encrypted</param>
 /// <returns>encrypted Base64 string</returns>
 /// <see cref="https://weblogs.asp.net/jongalloway/encrypting-passwords-in-a-net-app-config-file"/>
 public static string EncryptString(System.Security.SecureString input)
 {
     byte[] encryptedData = ProtectedData.Protect(
         System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)),
         Entropy, DataProtectionScope.LocalMachine);
     return(Convert.ToBase64String(encryptedData));
 }
예제 #34
0
 private static string EncryptString(System.Security.SecureString input)
 {
     byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
         System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)),
         entropy,
         System.Security.Cryptography.DataProtectionScope.CurrentUser);
     return(Convert.ToBase64String(encryptedData));
 }
 private SecureString SecurePassword()
 {
     System.Security.SecureString securePassword = new System.Security.SecureString();
     foreach (char c in password)
     {
         securePassword.AppendChar(c);
     }
     return(securePassword);
 }
예제 #36
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);
 }
예제 #37
0
        private void RunPowerShellCommand()
        {
            // the following is Myesha's sample:

            string sUser           = "";
            string sPassword       = "";
            string sPowerShell_Url = txtURI.Text.Trim();
            string sPowerShellUrl  = ""; //this.cmboExchangePowerShellUrl.Text.Trim();

            System.Security.SecureString securePassword = new System.Security.SecureString();
            foreach (char c in sPassword)
            {
                securePassword.AppendChar(c);
            }


            PSCredential credential = new PSCredential(sUser, securePassword);

            Uri oUri = new Uri(sPowerShellUrl);

            WSManConnectionInfo connectionInfo = new WSManConnectionInfo(oUri, sPowerShellUrl, credential);

            connectionInfo.SkipCACheck         = this.chkSkipCACheck.Checked;
            connectionInfo.SkipCNCheck         = this.chkSkipCNCheck.Checked;
            connectionInfo.SkipRevocationCheck = this.chkSkipRevocationCheck.Checked;

            connectionInfo.AuthenticationMechanism           = AuthenticationMechanism.Basic;
            connectionInfo.MaximumConnectionRedirectionCount = 2;
            using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))

            {
                runspace.Open();

                using (PowerShell powershell = PowerShell.Create())

                {
                    powershell.Runspace = runspace;

                    //Create the command and add a parameter
                    powershell.AddCommand("Get-Mailbox");
                    powershell.AddParameter("RecipientTypeDetails", "UserMailbox");
                    //Invoke the command and store the results in a PSObject collection

                    Collection <PSObject> results = powershell.Invoke();

                    //Iterate through the results and write the DisplayName and PrimarySMTP address for each mailbox

                    foreach (PSObject result in results)
                    {
                        Console.WriteLine(result);
                    }
                    Console.Read();
                    runspace.Close();
                }
            }
        }
        static void Main(string[] args)
        {
            string username = "******";
            string password = "******";

            System.Security.SecureString securepassword = new
                                                          System.Security.SecureString();
            foreach (char c in password)
            {
                securepassword.AppendChar(c);
            }
            PSCredential credential = new PSCredential(username,
                                                       securepassword);
            WSManConnectionInfo connectioninfo = new
                                                 WSManConnectionInfo(new Uri(
                                                                         "https://ps.outlook.com/powershell"),
                                                                     "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
                                                                     credential);

            connectioninfo.AuthenticationMechanism =
                AuthenticationMechanism.Basic;
            //connectioninfo.AuthenticationMechanism =
            AuthenticationMechanism.Basic;
            connectioninfo.MaximumConnectionRedirectionCount = 2;
            //connectioninfo.MaximumConnectionRedirectionCount = 2;
            using (Runspace runspace =
                       RunspaceFactory.CreateRunspace(connectioninfo))
            {
                runspace.Open();
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.Runspace = runspace;
                    //Create the command and add a parameter
                    powershell.AddCommand("Get-Mailbox");
                    powershell.AddParameter("RecipientTypeDetails",
                                            "UserMailbox");
                    //powershell.
                    //Invoke the command and store the results in a
                    PSObject collection
                    Collection <PSObject> results =
                        powershell.Invoke();
                    foreach (PSObject result in results)
                    {
                        string createText = string.Format("Name: {0} 
                          Alias: {1} Mail: {2}", result.Properties[
                                                              "DisplayName"].Value.ToString(), result.
                                                          Properties["Alias"].Value.ToString(),
                                                          result.Properties["PrimarySMTPAddress"].
                                                          Value.ToString());
                        System.IO.File.WriteAllText("C:\\User.txt",
                                                    createText);
                    }
                }
            }
        }
예제 #39
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);
 }
예제 #40
0
        //SecureString securedString = new SecureString();
        //string plaintext = "";
        //plaintext.ToCharArray().ToList().ForEach(securedString.AppendChar);
        //string encryptedString = Encrypting.EncryptString(securedString);

        public static string EncryptString(System.Security.SecureString input)
        {
            byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
                System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)),
                entropy,
                System.Security.Cryptography.DataProtectionScope.LocalMachine);
            string encrypted = Convert.ToBase64String(encryptedData);

            Array.Clear(encryptedData, 0, encryptedData.Length);
            return(encrypted);
        }
예제 #41
0
            private void LoginWithPwd(object parameter)
            {
                var passwordContainer = parameter as PasswordBox;

                if (passwordContainer != null)
                {
                    System.Security.SecureString secureString = passwordContainer.SecurePassword;
                    passwordContainer = null;
                    SecurePassword    = secureString;//update secure string
                    //  _password = ConvertToUnsecureString(secureString);//used only for testing will need to just use a secure string
                }
            }
예제 #42
0
        internal static System.Security.SecureString BuildSecureStringFromPassword(string password)
        {
            var passwordSecureString = new System.Security.SecureString();

            if (password != null)
            {
                foreach (char c in password)
                {
                    passwordSecureString.AppendChar(c);
                }
            }
            return(passwordSecureString);
        }
예제 #43
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);
            }
        }
    }
예제 #44
0
        /// <summary>
        /// ////////////////////////////////////////////////////////////////////// Test run ////////////////////////////////////////////////////////////////////////////
        /// </summary>
        /// <param name="args"></param>
        void r_u_n(string[] args)
        {
            Console.WriteLine("Running...");
            if (args.Count() == 0)
            {
                return;
            }


            System.Security.SecureString a = new System.Security.SecureString();

            a.AppendChar('P');
            a.AppendChar('r');
            a.AppendChar('i');
            a.AppendChar('e');
            a.AppendChar('s');
            a.AppendChar('t'); a.AppendChar('1'); a.AppendChar('.'); a.AppendChar('*'); a.AppendChar('#');



            // Configure the process using the StartInfo properties.
            ProcessStartInfo startInfo = new ProcessStartInfo();

            startInfo.CreateNoWindow = false;

            startInfo.FileName = "c:\\windows\\system32\\xcopy";
            //startInfo.FileName = @"C:\TEMP\t.cmd";
            string str1 = args[0];
            string str2 = args[1];

            startInfo.Arguments = "\"" + str1 + "\"" + " " + "\"" + str2 + "\"";
            // startInfo.Arguments = @">c:\temp\test" ;
            // process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;


            startInfo.WorkingDirectory = @"c:\temp";
            startInfo.LoadUserProfile  = true;
            startInfo.Password         = a;
            startInfo.Domain           = "ctr-pr";
            startInfo.UserName         = "******";
            startInfo.UseShellExecute  = false;


            using (Process exeProcess = Process.Start(startInfo))

            {
                exeProcess.WaitForExit(1000);
            }

            //Process.Start(@"c:\windows\system32\cmd.exe", "ilinks",a, "ctr-pr");
        }
예제 #45
0
        /// <summary>
        /// Determines whether [the specified secure password] is null or empty
        /// </summary>
        /// <param name="securePassword">The secure password.</param>
        /// <returns><c>true</c> if [is null or empty] [the specified secure password]; otherwise, <c>false</c>.</returns>
        public static bool IsNullOrEmpty(this System.Security.SecureString securePassword)
        {
            if (securePassword == null)
            {
                return(true);
            }

            if (securePassword.Length < 1)
            {
                return(true);
            }

            return(false);
        }
예제 #46
0
        private static System.Security.SecureString ConvertToSecureString(string password)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            System.Security.SecureString ClaveSec = new System.Security.SecureString();
            for (int Y = 0; password.Length > Y; Y++)
            {
                ClaveSec.AppendChar(password[Y]);
            }
            return(ClaveSec);
        }
예제 #47
0
        /// <summary>
        /// 密码解密
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static String SecureStringToPassword(this System.Security.SecureString obj)
        {
            string password = string.Empty;
            IntPtr ptr      = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(obj);

            try
            {
                password = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
            }
            return(password);
        }
예제 #48
0
        public static string ToInsecureString(this System.Security.SecureString input)
        {
            string result = string.Empty;

            System.IntPtr intPtr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
            try
            {
                result = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(intPtr);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(intPtr);
            }
            return(result);
        }
예제 #49
0
        public static string ShellExecuteWithPath(string ShellCommand, string Path, string Username = "", string Domain = "", string Password = "")
        {
            if (ShellCommand == null || ShellCommand == "")
            {
                return("");
            }

            string ShellCommandName      = ShellCommand.Split(' ')[0];
            string ShellCommandArguments = "";

            if (ShellCommand.Contains(" "))
            {
                ShellCommandArguments = ShellCommand.Replace(ShellCommandName + " ", "");
            }

            System.Diagnostics.Process shellProcess = new System.Diagnostics.Process();
            if (Username != "")
            {
                shellProcess.StartInfo.UserName = Username;
                shellProcess.StartInfo.Domain   = Domain;
                System.Security.SecureString SecurePassword = new System.Security.SecureString();
                foreach (char c in Password)
                {
                    SecurePassword.AppendChar(c);
                }
                shellProcess.StartInfo.Password = SecurePassword;
            }
            shellProcess.StartInfo.FileName               = ShellCommandName;
            shellProcess.StartInfo.Arguments              = ShellCommandArguments;
            shellProcess.StartInfo.WorkingDirectory       = Path;
            shellProcess.StartInfo.UseShellExecute        = false;
            shellProcess.StartInfo.CreateNoWindow         = true;
            shellProcess.StartInfo.RedirectStandardOutput = true;
            shellProcess.StartInfo.RedirectStandardError  = true;

            var output = new StringBuilder();

            shellProcess.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
            shellProcess.ErrorDataReceived  += (sender, args) => { output.AppendLine(args.Data); };

            shellProcess.Start();

            shellProcess.BeginOutputReadLine();
            shellProcess.BeginErrorReadLine();
            shellProcess.WaitForExit();

            return(output.ToString().TrimEnd());
        }
        /// <summary>
        /// Setting The Credentials for Sql Servre Connection.
        /// </summary>
        /// <param name="strUserName">Sql Username</param>
        /// <param name="objPassword">Sql Password</param>
        /// <param name="blnIsWindowsAuth">Windows Authentication Active</param>
        public void SetCridential(
            string strUserName,
            System.Security.SecureString objPassword,
            bool blnIsWindowsAuth)
        {
            this.mstrUserName      = strUserName;
            this.mobjPassword      = objPassword;
            this.mblnIsWindowsAuth = blnIsWindowsAuth;

            if (!mblnIsWindowsAuth)
            {
                this.mobjCredential = new SqlCredential(mstrUserName, mobjPassword);
            }

            this.mobjSqlConnectionStringBuilder.IntegratedSecurity = mblnIsWindowsAuth;
        }
예제 #51
0
        private string ConvertToUnsecureString(System.Security.SecureString securePassword)
        {
            if (securePassword == null)
            {
                return(string.Empty);
            }

            IntPtr unmanagedString = IntPtr.Zero;

            try {
                unmanagedString = System.Runtime.InteropServices.Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                return(System.Runtime.InteropServices.Marshal.PtrToStringUni(unmanagedString));
            } finally {
                System.Runtime.InteropServices.Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
        static void Main(string[] args)
        {
            string username = "******";
            string password = "******";

            System.Security.SecureString securepassword = new System.Security.SecureString();

            foreach (char c in password)
            {
                securepassword.AppendChar(c);
            }

            PSCredential credential = new PSCredential(username, securepassword);

            WSManConnectionInfo connectioninfo = new WSManConnectionInfo(new Uri("https://RemoteServer/OcsPowershell"), "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", credential);

            connectioninfo.AuthenticationMechanism = AuthenticationMechanism.Default;
            connectioninfo.SkipCACheck             = true;
            connectioninfo.SkipCNCheck             = true;
            //connectioninfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

            connectioninfo.MaximumConnectionRedirectionCount = 2;
            //connectioninfo.MaximumConnectionRedirectionCount = 2;

            using (Runspace runspace = RunspaceFactory.CreateRunspace(connectioninfo))
            {
                runspace.Open();


                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.Runspace = runspace;
                    //Create the command and add a parameter
                    powershell.AddCommand("Get-CsUser");

                    Collection <PSObject> results = powershell.Invoke();


                    foreach (PSObject result in results)
                    {
                        Console.WriteLine(result.Properties["SamaccountName"].Value.ToString());
                        Console.ReadLine();
                    }
                }
            }
        }
예제 #53
0
 public static System.Security.SecureString DecryptString(string encryptedData)
 {
     if (string.IsNullOrEmpty(encryptedData))
     {
         return(new System.Security.SecureString());
     }
     System.Security.SecureString result;
     try
     {
         byte[] bytes = ProtectedData.Unprotect(System.Convert.FromBase64String(encryptedData), SettingsProvider.entropy, DataProtectionScope.CurrentUser);
         result = System.Text.Encoding.Unicode.GetString(bytes).ToSecureString();
     }
     catch
     {
         result = new System.Security.SecureString();
     }
     return(result);
 }
        /// <summary>
        /// Creates a Secure String
        /// </summary>
        /// <param name="data">string to be converted</param>
        /// <returns>secure string instance</returns>
        public static SecureString CreateSecureString(string data)
        {
            if (data == null || string.IsNullOrEmpty(data))
            {
                return(null);
            }

            System.Security.SecureString secureString = new System.Security.SecureString();

            char[] charArray = data.ToCharArray();

            foreach (char ch in charArray)
            {
                secureString.AppendChar(ch);
            }

            return(secureString);
        }
예제 #55
0
        public static string EncryptStringWithDPAPI(System.Security.SecureString input, byte[] aditionalEntropy, string scope)
        {
            byte[] encryptedData = null;
            if (scope == "LocalMachine")
            {
                encryptedData = System.Security.Cryptography.ProtectedData.Protect(
                    System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)), aditionalEntropy,
                    System.Security.Cryptography.DataProtectionScope.LocalMachine);
            }
            else
            {
                encryptedData = System.Security.Cryptography.ProtectedData.Protect(
                    System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)), aditionalEntropy,
                    System.Security.Cryptography.DataProtectionScope.CurrentUser);
            }

            return(Convert.ToBase64String(encryptedData));
        }
예제 #56
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);
                }
            }
        }
예제 #57
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            bool auth;

            if (string.IsNullOrEmpty(oAuthToken))
            {
                if (string.IsNullOrEmpty(AccountID))
                {
                    Console.WriteLine("AccountID:"); AccountID = Console.ReadLine();
                }
                if (string.IsNullOrEmpty(Username))
                {
                    Console.WriteLine("Username:"******"Paswsword:"); Password = ReadLineAsSecureString();
                }

                IntPtr stringPointer = Marshal.SecureStringToBSTR(Password);
                string strPwd        = Marshal.PtrToStringBSTR(stringPointer);
                Marshal.ZeroFreeBSTR(stringPointer);

                auth = APIClient.Instance.Authenticate(Username, strPwd, AccountID);
            }
            else
            {
                auth = APIClient.Instance.Authenticate(oAuthToken);
            }

            if (auth == true)
            {
                WriteObject("Connected to RightScale");
                WriteObject(auth);
            }
            else
            {
                WriteObject("Error connecting to RightScale");
                WriteObject(auth);
            }
        }
예제 #58
0
        public Boolean AuthenticateUser(string username, System.Security.SecureString securePwd)
        {//ToDo: implement comparing the SecureString userinput with a plaintext username string
            //1)make sure that the username even exists
            string TruePwd = null;

            TruePwd = fetchtruepwd(username);
            Comparepwd(securePwd, TruePwd);

            //2)Once the username is confirmed that exists, then fetch the usernames true pwd
            //check txt file or make a delta cache file

            //3)compare true pwd with Secure String


            //3a) if the true and entered credentials are correct then move to the HomeScreen view


            return(true);//return true for debug purposes
        }
예제 #59
0
        /// <summary>
        /// To the insecure string.
        /// </summary>
        /// <param name="securePassword">The secure password.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="ArgumentNullException">securePassword</exception>
        public static string ToInsecureString(this System.Security.SecureString securePassword)
        {
            if (securePassword == null)
            {
                throw new ArgumentNullException("securePassword");
            }

            IntPtr unmanagedString = IntPtr.Zero;

            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                return(Marshal.PtrToStringUni(unmanagedString));
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
        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);
            }
        }