Ejemplo n.º 1
0
        /// <summary>
        /// Create a new self signed certificate
        /// </summary>
        /// <param name="x500"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="insecurePassword"></param>
        /// <returns></returns>
        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;
        }
Ejemplo n.º 2
0
        public PersistenceList(Stream connectionStream, bool doSecure = false, bool liveOpen = true, CompressionMode compression = CompressionMode.NoCompression)
        {
            if (!this.IsSerializable(typeof(T)))
            {
                throw new System.Runtime.Serialization.SerializationException("The class is not serializable");
            }

            temporalFile = Path.GetTempFileName();
            tfc.AddFile(temporalFile, false);
            this.liveOpen       = liveOpen;
            this.useCompression = compression;

            if (doSecure)
            {
                this.password = new System.Security.SecureString();
                Enumerable.Concat(Path.GetRandomFileName(), Path.GetRandomFileName().Reverse())
                .ToList().ForEach(password.AppendChar);
                password.MakeReadOnly();
            }

            if (connectionStream != null)
            {
                using (FileStream fileStream = new FileStream(temporalFile, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                {
                    connectionStream.CopyTo(fileStream);
                    fileStream.Flush();
                }
            }
        }
Ejemplo n.º 3
0
 static System.Security.SecureString getPassword()
 {
     System.Security.SecureString pwd = new System.Security.SecureString();
     while (true)
     {
         System.ConsoleKeyInfo i = System.Console.ReadKey(true);
         if (i.Key == System.ConsoleKey.Enter)
         {
             System.Console.WriteLine();
             break;
         }
         else if (i.Key == System.ConsoleKey.Backspace)
         {
             if (pwd.Length > 0)
             {
                 pwd.RemoveAt(pwd.Length - 1);
                 System.Console.Write("\b \b");
             }
         }
         else
         {
             pwd.AppendChar(i.KeyChar);
             System.Console.Write("*");
         }
     }
     pwd.MakeReadOnly();
     return(pwd);
 }
Ejemplo n.º 4
0
        /// <summary>建立自签名证书</summary>
        /// <param name="x500"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="insecurePassword"></param>
        /// <returns></returns>
        public static Byte[] CreateSelfSignCertificatePfx(String x500, DateTime startTime, DateTime endTime, String insecurePassword)
        {
            SecureString password = null;

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

                    password.MakeReadOnly();
                }

                return(CreateSelfSignCertificatePfx(x500, startTime, endTime, password));
            }
            finally
            {
                if (password != null)
                {
                    password.Dispose();
                }
            }
        }
Ejemplo n.º 5
0
        void kedofriends(bool retry)
        {
            using (jaka jaka = new jaka())
            {
                jaka.Show();

                if (retry)
                {
                    jaka.PasswordWasWrong();
                    npkji.Flash(jaka, 3);
                }

                // wait for slow jaka
                while (jaka.Visible)
                {
                    Application.DoEvents();

                    Thread.Sleep(1);
                }

                // jaka stinx
                if (jaka.WasCancelled || jaka.Username.Length == 0 || jaka.Password.Length == 0)
                    Environment.Exit(0);

                username = jaka.Username;
                type = jaka.PlanType;

                password = new System.Security.SecureString();
                foreach (var x in jaka.Password) password.AppendChar(x);
                password.MakeReadOnly();
            }
        }
Ejemplo n.º 6
0
 static System.Security.SecureString getPassword()
 {
     System.Security.SecureString pwd = new System.Security.SecureString();
      while (true)
      {
     System.ConsoleKeyInfo i = System.Console.ReadKey(true);
     if (i.Key == System.ConsoleKey.Enter)
     {
        System.Console.WriteLine();
        break;
     }
     else if (i.Key == System.ConsoleKey.Backspace)
     {
        if (pwd.Length > 0)
        {
           pwd.RemoveAt(pwd.Length - 1);
           System.Console.Write("\b \b");
        }
     }
     else
     {
        pwd.AppendChar(i.KeyChar);
        System.Console.Write("*");
     }
      }
      pwd.MakeReadOnly();
      return pwd;
 }
 /// <summary>
 /// Convert String To SecureString.
 /// </summary>
 /// <param name="stringToSecure"></param>
 /// <returns></returns>
 public static System.Security.SecureString ToSecureString(this string stringToSecure)
 {
     // Not using Idisposable.
     System.Security.SecureString secureString = new  System.Security.SecureString();
     stringToSecure.ToCharArray().ToList().ForEach(c => secureString.AppendChar(c));
     secureString.MakeReadOnly();
     return(secureString);
 }
Ejemplo n.º 8
0
 string HashFiveByFiveWithoutFormatting(string fiveByFive)
 {
     using (var tokenCode = new System.Security.SecureString())
     {
         fiveByFive.Replace("-", string.Empty).ForEach(tokenCode.AppendChar);
         tokenCode.MakeReadOnly();
         return(tokenSecurity.HashAsBase64(tokenCode));
     }
 }
Ejemplo n.º 9
0
 public static System.Security.SecureString ToSecureString(string input)
 {
     var secure = new System.Security.SecureString();
     foreach (var c in input)
     {
         secure.AppendChar(c);
     }
     secure.MakeReadOnly();
     return secure;
 }
Ejemplo n.º 10
0
 /// <summary>
 /// 密码加密
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static System.Security.SecureString ToPasswordToSecureString(this string obj)
 {
     System.Security.SecureString ss = new System.Security.SecureString();
     obj.ToStringExtension().ToArray().ToList().ForEach(x =>
     {
         ss.AppendChar(x);
     });
     ss.MakeReadOnly();
     return(ss);
 }
Ejemplo n.º 11
0
        private System.Security.SecureString GetSecureString(string str)
        {
            var ssr = new System.Security.SecureString();

            foreach (char c in str)
            {
                ssr.AppendChar(c);
            }
            ssr.MakeReadOnly();
            return(ssr);
        }
Ejemplo n.º 12
0
        public static System.Security.SecureString ToSecureString(string input)
        {
            var ret = new System.Security.SecureString();

            foreach (var cb in input)
            {
                ret.AppendChar(cb);
            }
            ret.MakeReadOnly();
            input = string.Empty;
            return(ret);
        }
Ejemplo n.º 13
0
        public static System.Security.SecureString ToSecureString(this string text)
        {
            var securePassword = new System.Security.SecureString();

            foreach (var c in text)
            {
                securePassword.AppendChar(c);
            }

            securePassword.MakeReadOnly();
            return(securePassword);
        }
Ejemplo n.º 14
0
        protected void setConnectionString(string connectionString, string username, string password)
        {
            System.Security.SecureString securePassword = new System.Security.SecureString();
            foreach (char character in password)
            {
                securePassword.AppendChar(character);
            }
            securePassword.MakeReadOnly();
            var credentials = new SqlCredential(username, securePassword);

            this._connection = new SqlConnection(connectionString, credentials);
        }
Ejemplo n.º 15
0
        public void NewConectionInvalidInput()
        {
            // Create fake credentials to test with
            var Cipher = new System.Security.SecureString();

            foreach (char c in Pwd)
            {
                Cipher.AppendChar(c);
            }

            // Test the attempt to create without ReadOnly password
            try
            {
                SqlConn.New(ConStr2, UsrNm, Cipher);
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("password must be marked as read only.", ae.Message);
            }

            // Make ReadOnly and continue testing
            Cipher.MakeReadOnly();
            var Cred = new SqlCredential(UsrNm, Cipher);

            // Test the attempt to create with IntegratedSecurity = True and Credentials
            try
            {
                SqlConn.New(ConStr, Cred);
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("Cannot use Credential with Integrated Security connection string keyword.", ae.Message);
            }

            // Test the attempt to create with null Credentials
            try
            {
                SqlConn.New(ConStr2, null, "");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("Value cannot be null.\r\nParameter name: userId", ae.Message);
            }
            try
            {
                SqlConn.New(ConStr2, null, new System.Security.SecureString());
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("Value cannot be null.\r\nParameter name: userId", ae.Message);
            }
        }
Ejemplo n.º 16
0
 public System.Security.SecureString DecryptToSecureStringFromBase64(string inString)
 {
     byte[] bytes = Convert.FromBase64String(inString);
     bytes = Decrypt(bytes);
     System.Security.SecureString ret = new System.Security.SecureString();
     for (int i = 0; i < bytes.Length; i += 2)
     {
         ret.AppendChar((char)(bytes[i] * 256 + bytes[i + 1]));
         bytes[i] = bytes[i + 1] = 0;
     }
     ret.MakeReadOnly();
     return(ret);
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Decrypts the currently EncryptedCharacterName if possible, populating SecureCharacterName (which can then be used to log in...)
        /// </summary>
        public void DecryptCharacterName(bool allowPopup)
        {
            if (string.IsNullOrEmpty(EncryptedCharacterName) || string.IsNullOrEmpty(EncryptedCharacterNameIV))
            {
                // no CharacterName stored to decrypt.
                return;
            }
            // CharacterName is indeed encrypted

            if (!App.Settings.HasPasswordMasterKey)
            {
                // Master CharacterName not yet entered
                if (!allowPopup)
                {
                    // can't ask for it right now
                    return;
                }

                // ok, ask for it
                if (!App.Settings.RequestMasterPassword())
                {
                    // not entered. can't decrypt.
                    return;
                }
            }
            using (RijndaelManaged rjm = new RijndaelManaged())
            {
                rjm.IV = Convert.FromBase64String(EncryptedCharacterNameIV);

                using (SecureBytesWrapper sbwKey = new SecureBytesWrapper(App.Settings.PasswordMasterKey, true))
                {
                    rjm.Key = sbwKey.Bytes;
                    using (ICryptoTransform decryptor = rjm.CreateDecryptor())
                    {
                        byte[] pass = Convert.FromBase64String(EncryptedCharacterName);

                        using (SecureBytesWrapper sbw = new SecureBytesWrapper())
                        {
                            sbw.Bytes = decryptor.TransformFinalBlock(pass, 0, pass.Length);

                            SecureCharacterName = new System.Security.SecureString();
                            foreach (char c in Encoding.Unicode.GetChars(sbw.Bytes))
                            {
                                SecureCharacterName.AppendChar(c);
                            }
                            SecureCharacterName.MakeReadOnly();
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public static System.Security.SecureString ToSecureString(this string source)
        {
            var plain = source ?? string.Empty;

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

            foreach (var chr in plain.ToCharArray())
            {
                secureString.AppendChar(chr);
            }

            secureString.MakeReadOnly();

            return(secureString);
        }
Ejemplo n.º 19
0
        // <summary>Build a new SqlConnection object</summary>
        // <param name="ConnectionString" type="string">The connection string to utilize in the new SqlConnection object</param>
        // <param name="Username" type="string">The username of credentails to utilize in the new SqlConnection object</param>
        // <param name="Password" type="string">The plaintext password of credentials to utilize in the new SqlConnection object</param>
        // <return>SqlConnection</return>
        public static SqlConnection New(string ConnectionString, string Username, string Password)
        {
            // Convert the plaintext Password in to a SecureString object
            var Ciphertext = new System.Security.SecureString();

            foreach (char c in Password)
            {
                Ciphertext.AppendChar(c);
            }
            Ciphertext.MakeReadOnly();
            // Make a SqlCredential using the provided Username and ciphertext Password
            var Credential = new SqlCredential(Username, Ciphertext);

            return(new SqlConnection(ConnectionString, Credential)); // Return new SqlConnection using ConnectionString and Credential
        }
Ejemplo n.º 20
0
        private System.Security.SecureString ConvertToSecureString(string password)
        {
            if (password == null)
            {
                throw new ArgumentNullException("missing pwd");
            }

            var securePassword = new System.Security.SecureString();

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

            securePassword.MakeReadOnly();
            return(securePassword);
        }
Ejemplo n.º 21
0
        public void NewConectionValidInput()
        {
            // Test the creation of a basic SqlConnection object
            var Con = SqlConn.New(ConStr);

            Assert.AreEqual(ConStr, Con.ConnectionString);
            Assert.IsNull(Con.Credential);
            Con = null;

            // Create fake credentials to test with
            var Cipher = new System.Security.SecureString();

            foreach (char c in Pwd)
            {
                Cipher.AppendChar(c);
            }
            Cipher.MakeReadOnly();
            var Cred = new SqlCredential(UsrNm, Cipher);

            // Test the creation of a SqlConnection object with credentials
            Con = SqlConn.New(ConStr2, Cred);
            Assert.AreEqual(ConStr2, Con.ConnectionString);
            Assert.IsNotNull(Con.Credential);
            Assert.AreEqual(UsrNm, Con.Credential.UserId);
            Assert.AreEqual(Cipher, Con.Credential.Password);
            Con = null;

            // Test the creation of a SqlConnection object with Username and Secure Password
            Con = SqlConn.New(ConStr2, UsrNm, Cipher);
            Assert.AreEqual(ConStr2, Con.ConnectionString);
            Assert.IsNotNull(Con.Credential);
            Assert.AreEqual(UsrNm, Con.Credential.UserId);
            Assert.AreEqual(Cipher, Con.Credential.Password);
            Con = null;

            // Test the creation of a SqlConnection object with Username and Plaintext Password
            Con = SqlConn.New(ConStr2, UsrNm, Pwd);
            Assert.AreEqual(ConStr2, Con.ConnectionString);
            Assert.IsNotNull(Con.Credential);
            Assert.AreEqual(UsrNm, Con.Credential.UserId);
            Assert.AreNotEqual(Cipher, Con.Credential.Password);
        }
Ejemplo n.º 22
0
        public void AddCustomers()
        {
            DB.connString = @"Data Source=MIBOOK\SQLEXPRESS;Initial Catalog=miCRM;Integrated Security=False;Connect Timeout=5;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
            System.Security.SecureString pwd = new System.Security.SecureString();
            pwd.MakeReadOnly();
            DB.credentials = new SqlCredential("miraklis", pwd);
            Customer cust;

            for (int i = 0; i < 10000; i++)
            {
                cust = new Customer
                {
                    FirstName   = "First Name" + i.ToString(),
                    LastName    = "Last Name" + i.ToString(),
                    DateOfBirth = DateTime.Now,
                    CompanyId   = ((i % 2) + 1)
                };
                DB.AddCustomer(cust);
            }
            Assert.IsTrue(true);
        }
Ejemplo n.º 23
0
        public static System.Security.SecureString GetPasswordAsSecureString(string prompt, ConsoleColor?promptColor = null, ConsoleColor?promptBgColor = null)
        {
            var secureString = new System.Security.SecureString();

            foreach (var key in ReadObfuscatedLine(prompt, promptColor, promptBgColor))
            {
                switch (key)
                {
                case Backspace:
                    secureString.RemoveAt(secureString.Length - 1);
                    break;

                default:
                    secureString.AppendChar(key);
                    break;
                }
            }

            secureString.MakeReadOnly();
            return(secureString);
        }
Ejemplo n.º 24
0
        /// <summary>http://devdistrict.com/codedetails.aspx?A=405</summary>
        public static void SecureStringStub()
        {
            /*
             * Building the SecureString
             * To put data into the secure string you need to feed it one character at a time. Alternatively you can give the constructor a pointer to an array of characters to load the data in.
             */
            System.Security.SecureString secureData = new System.Security.SecureString();
            secureData.AppendChar('M');
            secureData.AppendChar('y');
            secureData.AppendChar('P');
            secureData.AppendChar('a');
            secureData.AppendChar('s');
            secureData.AppendChar('s');
            secureData.AppendChar('w');
            secureData.AppendChar('o');
            secureData.AppendChar('r');
            secureData.AppendChar('d');

            /*
             * Pinning the SecureString
             *  Once you are done feeding data into the SecureString you need to call the MakeReadOnly() method. This makes the string immutable, and pins the location of the string in memory so the .NET Framework doesn't move it around.
             *  Make it immutable
             */
            secureData.MakeReadOnly();

            /*
             * Reading from a SecureString
             * Reading the data from the SecureString is a bit of a pain, having to use Interop.
             * NOTE: This code is for instruction only and is not secure since we read the value of our SecureString into a normal string thus defeating our own security.
             */
            IntPtr ptr          = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(secureData);
            string unsecureData = System.Runtime.InteropServices.Marshal.PtrToStringUni(ptr);

            /*
             * Clean up when your done!
             * Always clean up when your done with your SecureString. You can easily do this by calling the Dispose method. This deletes the data from memory.
             */
            secureData.Dispose();
        }
Ejemplo n.º 25
0
        internal 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);
        }
Ejemplo n.º 26
0
        static void SharepointWorker()
        {
            string userName = "******";
            string password = "******";
            string siteUrl  = "https://archimatika.sharepoint.com/sites/TestSiteForCustomization";

            ClientContext clientContext = new ClientContext(siteUrl);

            //Simple auth
            System.Security.SecureString ssPass = new System.Security.SecureString();
            foreach (char c in password)
            {
                ssPass.AppendChar(c);
            }
            ssPass.MakeReadOnly();

            clientContext.Credentials = new SharePointOnlineCredentials(userName, ssPass);
            clientContext.Load(clientContext.Web, web => web.Title);
            clientContext.ExecuteQuery();

            //Get List
            SP.List oList      = clientContext.Web.Lists.GetByTitle("TestList");
            var     listFields = oList.Fields;

            clientContext.Load(listFields, fields => fields.Include(field => field.Title, field => field.InternalName));
            clientContext.ExecuteQuery();

            //Add record to list
            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
            ListItem oListItem = oList.AddItem(itemCreateInfo);

            oListItem["Title"]             = "PRJ-STG-BLD-R-SBS-001";
            oListItem["GDrive_x002d_GUID"] = "530EC012-0AEC-4C13-B613-152F65416E37";

            oListItem.Update();

            clientContext.ExecuteQuery();
        }
Ejemplo n.º 27
0
        void kedofriends(bool retry)
        {
            using (jaka jaka = new jaka())
            {
                jaka.Show();

                if (retry)
                {
                    jaka.PasswordWasWrong();
                    npkji.Flash(jaka, 3);
                }

                // wait for slow jaka
                while (jaka.Visible)
                {
                    Application.DoEvents();

                    Thread.Sleep(1);
                }

                // jaka stinx
                if (jaka.WasCancelled || jaka.Username.Length == 0 || jaka.Password.Length == 0)
                {
                    Environment.Exit(0);
                }

                username = jaka.Username;
                type     = jaka.PlanType;

                password = new System.Security.SecureString();
                foreach (var x in jaka.Password)
                {
                    password.AppendChar(x);
                }
                password.MakeReadOnly();
            }
        }
Ejemplo n.º 28
0
        public LoginResult GetCharacterChallenge(bool sisi, out Token accessToken)
        {
            // need SecureCharacterName.
            if (SecureCharacterName == null || SecureCharacterName.Length == 0)
            {
                DecryptCharacterName(true);
                if (SecureCharacterName == null || SecureCharacterName.Length == 0)
                {
                    Windows.CharacterChallengeWindow ccw = new Windows.CharacterChallengeWindow(this);
                    bool?result = ccw.ShowDialog();

                    if (string.IsNullOrWhiteSpace(ccw.CharacterName))
                    {
                        // CharacterName is required, sorry dude
                        accessToken = null;
                        //  SecurePassword = null;
                        SecureCharacterName = null;
                        return(LoginResult.InvalidCharacterChallenge);
                    }

                    SecureCharacterName = new System.Security.SecureString();
                    foreach (char c in ccw.CharacterName)
                    {
                        SecureCharacterName.AppendChar(c);
                    }
                    SecureCharacterName.MakeReadOnly();
                    EncryptCharacterName();
                    App.Settings.Store();
                }
            }

            string uri = "https://login.eveonline.com/Account/Challenge?ReturnUrl=%2Foauth%2Fauthorize%2F%3Fclient_id%3DeveLauncherTQ%26lang%3Den%26response_type%3Dtoken%26redirect_uri%3Dhttps%3A%2F%2Flogin.eveonline.com%2Flauncher%3Fclient_id%3DeveLauncherTQ%26scope%3DeveClientToken";

            if (sisi)
            {
                uri = "https://sisilogin.testeveonline.com/Account/Challenge?ReturnUrl=%2Foauth%2Fauthorize%2F%3Fclient_id%3DeveLauncherTQ%26lang%3Den%26response_type%3Dtoken%26redirect_uri%3Dhttps%3A%2F%2Fsisilogin.testeveonline.com%2Flauncher%3Fclient_id%3DeveLauncherTQ%26scope%3DeveClientToken";
            }

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);

            req.Timeout           = 30000;
            req.AllowAutoRedirect = true;
            if (!sisi)
            {
                req.Headers.Add("Origin", "https://login.eveonline.com");
            }
            else
            {
                req.Headers.Add("Origin", "https://sisilogin.testeveonline.com");
            }
            req.Referer         = uri;
            req.CookieContainer = Cookies;
            req.Method          = "POST";
            req.ContentType     = "application/x-www-form-urlencoded";
            using (SecureBytesWrapper body = new SecureBytesWrapper())
            {
                byte[] body1 = Encoding.ASCII.GetBytes(String.Format("RememberCharacterChallenge={0}&Challenge=", "true"));
                using (SecureStringWrapper ssw = new SecureStringWrapper(SecureCharacterName, Encoding.ASCII))
                {
                    using (SecureBytesWrapper escapedCharacterName = new SecureBytesWrapper())
                    {
                        escapedCharacterName.Bytes = System.Web.HttpUtility.UrlEncodeToBytes(ssw.ToByteArray());

                        body.Bytes = new byte[body1.Length + escapedCharacterName.Bytes.Length];
                        System.Buffer.BlockCopy(body1, 0, body.Bytes, 0, body1.Length);
                        System.Buffer.BlockCopy(escapedCharacterName.Bytes, 0, body.Bytes, body1.Length, escapedCharacterName.Bytes.Length);
                    }
                }

                req.ContentLength = body.Bytes.Length;
                try
                {
                    using (Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(body.Bytes, 0, body.Bytes.Length);
                    }
                }
                catch (System.Net.WebException e)
                {
                    switch (e.Status)
                    {
                    case WebExceptionStatus.Timeout:
                    {
                        accessToken = null;
                        return(LoginResult.Timeout);
                    }

                    default:
                        throw;
                    }
                }
            }
            return(GetAccessToken(sisi, req, out accessToken));
        }
Ejemplo n.º 29
0
        public LoginResult GetCharacterChallenge(bool sisi, out Token accessToken)
        {
            // need SecureCharacterName.
            if (SecureCharacterName == null || SecureCharacterName.Length == 0)
            {
                DecryptCharacterName(true);
                if (SecureCharacterName == null || SecureCharacterName.Length == 0)
                {
                    Windows.CharacterChallengeWindow ccw = new Windows.CharacterChallengeWindow(this);
                    bool?result = ccw.ShowDialog();

                    if (string.IsNullOrWhiteSpace(ccw.CharacterName))
                    {
                        // CharacterName is required, sorry dude
                        accessToken = null;
                        //  SecurePassword = null;
                        SecureCharacterName = null;
                        return(LoginResult.InvalidCharacterChallenge);
                    }

                    SecureCharacterName = new System.Security.SecureString();
                    foreach (char c in ccw.CharacterName)
                    {
                        SecureCharacterName.AppendChar(c);
                    }
                    SecureCharacterName.MakeReadOnly();
                    EncryptCharacterName();
                    App.Settings.Store();
                }
            }

            var uri = RequestResponse.GetCharacterChallengeUri(sisi, state.ToString(), challengeHash);
            var req = RequestResponse.CreatePostRequest(uri, sisi, true, uri.ToString(), Cookies);

            using (SecureBytesWrapper body = new SecureBytesWrapper())
            {
                byte[] body1 = Encoding.ASCII.GetBytes(String.Format("RememberCharacterChallenge={0}&Challenge=", "true"));
                using (SecureStringWrapper ssw = new SecureStringWrapper(SecureCharacterName, Encoding.ASCII))
                {
                    using (SecureBytesWrapper escapedCharacterName = new SecureBytesWrapper())
                    {
                        escapedCharacterName.Bytes = System.Web.HttpUtility.UrlEncodeToBytes(ssw.ToByteArray());

                        body.Bytes = new byte[body1.Length + escapedCharacterName.Bytes.Length];
                        System.Buffer.BlockCopy(body1, 0, body.Bytes, 0, body1.Length);
                        System.Buffer.BlockCopy(escapedCharacterName.Bytes, 0, body.Bytes, body1.Length, escapedCharacterName.Bytes.Length);
                    }
                }

                req.ContentLength = body.Bytes.Length;
                try
                {
                    using (Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(body.Bytes, 0, body.Bytes.Length);
                    }
                }
                catch (System.Net.WebException e)
                {
                    switch (e.Status)
                    {
                    case WebExceptionStatus.Timeout:
                    {
                        accessToken = null;
                        return(LoginResult.Timeout);
                    }

                    default:
                        throw;
                    }
                }
            }
            return(GetAccessToken(sisi, req, out accessToken));
        }
Ejemplo n.º 30
0
 public EncryptedString(byte[] key)
 {
     str = new System.Security.SecureString();
     str.MakeReadOnly();
     encr = new EncryptionHelper(key);
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Authenticate user/application using Credentials.
        /// </summary>
        /// <param name="Credentials">Credentials to use during authentication process.</param>
        public static async System.Threading.Tasks.Task AuthenticateAsync(SoftmakeAll.SDK.Fluent.Authentication.ICredentials Credentials)
        {
            if (Credentials != null)
            {
                SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = Credentials;

                // From AccessKey
                if (Credentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application)
                {
                    SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Basic {System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{Credentials.ClientID}@{Credentials.ContextIdentifier.ToString().ToLower()}:{Credentials.ClientSecret}"))}";
                    SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Store();
                    await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization);

                    return;
                }
            }
            else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials == null)
            {
                try
                {
                    System.Text.Json.JsonElement CacheData = SoftmakeAll.SDK.Fluent.GeneralCacheHelper.ReadString().ToJsonElement();
                    if (!(CacheData.IsValid()))
                    {
                        throw new System.Exception();
                    }

                    // From AccessKey
                    if (CacheData.GetInt32("AuthType") == (int)SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application)
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = new SoftmakeAll.SDK.Fluent.Authentication.Credentials(CacheData.GetGuid("ContextIdentifier"), CacheData.GetString("ClientID"), null, (SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes)CacheData.GetInt32("AuthType"));
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = CacheData.GetString("Authorization");
                        if (System.String.IsNullOrWhiteSpace(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization))
                        {
                            throw new System.Exception();
                        }

                        await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization);

                        return;
                    }
                    else
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = new SoftmakeAll.SDK.Fluent.Authentication.Credentials(CacheData.GetJsonElement("AppMetadata").EnumerateObject().First().Value.GetGuid("client_id"));
                        SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType = SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive;
                    }
                }
                catch { }
            }

            if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials == null)
            {
                SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                throw new System.Exception("Invalid Credentials from cache.");
            }


            // From AccessKey
            if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application)
            {
                return;
            }


            // From Public Client Application
            if ((SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult == null) || (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.ExpiresOn.Subtract(System.DateTimeOffset.UtcNow).TotalMinutes <= 5.0D))
            {
                System.String[] Scopes = new System.String[] { "openid", "https://softmakeb2c.onmicrosoft.com/48512da7-b030-4e62-be61-9e19b2c52d8a/user_impersonation" };
                if (SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication == null)
                {
                    if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive) // From Interactive
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication = SoftmakeAll.SDK.Fluent.SDKContext.CreatePublicClientApplication(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ContextIdentifier, "A_signup_signin", "http://localhost:1435");
                    }
                    else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Credentials) // From Username and Password
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication = SoftmakeAll.SDK.Fluent.SDKContext.CreatePublicClientApplication(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ContextIdentifier, "_ROPC");
                    }
                    else
                    {
                        throw new System.Exception("Invalid authentication type.");
                    }
                }

                // Getting existing Account in cache
                try
                {
                    System.Collections.Generic.IEnumerable <Microsoft.Identity.Client.IAccount> Accounts = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.GetAccountsAsync();

                    if (Accounts.Any())
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenSilent(Scopes, Accounts.FirstOrDefault()).ExecuteAsync();

                        if (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult != null)
                        {
                            SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Bearer {SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken}";
                            await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken);

                            return;
                        }
                    }
                }
                catch
                {
                    SoftmakeAll.SDK.Fluent.GeneralCacheHelper.Clear();
                }


                if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive) // From Interactive
                {
                    try
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenInteractive(Scopes).WithPrompt(Microsoft.Identity.Client.Prompt.ForceLogin).ExecuteAsync();
                    }
                    catch { }
                }
                else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Credentials) // From Username and Password
                {
                    if (System.String.IsNullOrWhiteSpace(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientSecret))
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                        throw new System.Exception("Authentication aborted. Please, re-enter credentials.");
                    }

                    System.Security.SecureString Password = new System.Security.SecureString();
                    foreach (System.Char Char in SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientSecret)
                    {
                        Password.AppendChar(Char);
                    }
                    Password.MakeReadOnly();

                    try
                    {
                        SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenByUsernamePassword(Scopes, SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientID, Password).ExecuteAsync();

                        Password.Dispose();
                    }
                    catch
                    {
                        Password.Dispose();
                        SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                        throw new System.Exception("Invalid username or password.");
                    }
                }

                if (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult == null)
                {
                    SoftmakeAll.SDK.Fluent.SDKContext.SignOut();
                    throw new System.Exception("Authentication aborted.");
                }


                SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Bearer {SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken}";
                await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken);

                return;
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Decrypts the specified data using a 256-bit cipher. The key can be any length.
        /// </summary>
        /// <param name="Data">The data to be decrypted. Will be converted to UTF8.</param>
        /// <param name="Key">The key used to decrypt the data.</param>
        /// <returns>A string containing the decoded data.</returns>
        public static System.Security.SecureString Decrypt256StringSecure(Stream Data, byte[] Key)
        {
            RijndaelManaged AES = null;
            CryptoStream CS = null;
            StreamReader DS = null;
            try
            {
                //Get the IV and length corrected Key.
                KeyData KeyData = GenerateKeyIV128(Key);
                //Create the AES crytpograhy object.
                AES = new RijndaelManaged { BlockSize = 256, KeySize = 256, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
                CS = new CryptoStream(Data, AES.CreateDecryptor(), CryptoStreamMode.Read);
                DS = new StreamReader(CS);

                var ss = new System.Security.SecureString();
                while (DS.EndOfStream == false)
                    ss.AppendChar(Convert.ToChar(DS.Read()));
                ss.MakeReadOnly();
                return ss;
            }
            finally
            {
                if (AES != null) AES.Clear();
                if (CS != null) CS.Dispose();
                if (DS != null) DS.Dispose();
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Decrypts the specified data using a 192-bit cipher. The key can be any length.
        /// </summary>
        /// <param name="Data">The data to be decrypted. Will be converted to UTF8.</param>
        /// <param name="Key">The key used to decrypt the data.</param>
        /// <returns>A string containing the decoded data.</returns>
        public static System.Security.SecureString Decrypt192StringSecure(byte[] Data, byte[] Key)
        {
            AesCryptoServiceProvider AES = null;
            var MS = new MemoryStream(Data);
            CryptoStream CS = null;
            StreamReader DS = null;
            try
            {
                //Get the IV and length corrected Key.
                KeyData KeyData = GenerateKeyIV128(Key);
                //Create the AES crytpograhy object.
                AES = new AesCryptoServiceProvider { BlockSize = 192, KeySize = 192, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
                CS = new CryptoStream(MS, AES.CreateDecryptor(), CryptoStreamMode.Read);
                DS = new StreamReader(CS, System.Text.Encoding.UTF8);

                var ss = new System.Security.SecureString();
                while (DS.EndOfStream == false)
                    ss.AppendChar(Convert.ToChar(DS.Read()));
                ss.MakeReadOnly();
                return ss;
            }
            finally
            {
                if (AES != null) AES.Clear();
                MS.Dispose();
                if (CS != null) CS.Dispose();
                if (DS != null) DS.Dispose();
            }
        }
Ejemplo n.º 34
0
        /*
         * Method:	    RunScript
         * Purpose:	    Creates two shared datasources on report server in home folder, by invoking powershell runspace
         * Parameters:	sctipt string, int mode 1 - create ERP datasource 2 - create LYNQ datasource, reporting server URL as a string, server name as a string, database name as a string,
         *              user name as a string, password as a string
         * Return:		void
         */
        public static void RunScript(string scriptText, int mode, string txtReportingServerURL, string txtServer, string txtDatabase, string txtUserName, string txtPassword)
        {
            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it
            runspace.Open();

            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();

            pipeline.Commands.AddScript(scriptText);


            pipeline.Invoke();
            pipeline.Commands.Clear();


            Command myCommand = new Command("New-SSRSDataSource");

            if (mode == 1)
            {
                CommandParameter dsName = new CommandParameter("DataSourceName", "LYNQmomERP");
                myCommand.Parameters.Add(dsName);

                CommandParameter dsPath = new CommandParameter("path", "/");
                myCommand.Parameters.Add(dsPath);
                CommandParameter dsReportWebService = new CommandParameter("reportWebService", txtReportingServerURL);
                myCommand.Parameters.Add(dsReportWebService);
                CommandParameter dsConnectionString = new CommandParameter("connectString", "Data Source = " + txtServer + "; Initial Catalog = " + txtDatabase);
                myCommand.Parameters.Add(dsConnectionString);
            }
            else
            {
                CommandParameter dsName = new CommandParameter("DataSourceName", "LYNQmom");
                myCommand.Parameters.Add(dsName);
                CommandParameter dsPath = new CommandParameter("path", "/");
                myCommand.Parameters.Add(dsPath);
                CommandParameter dsReportWebService = new CommandParameter("reportWebService", txtReportingServerURL);
                myCommand.Parameters.Add(dsReportWebService);
                CommandParameter dsConnectionString = new CommandParameter("connectString", "Data Source = " + txtServer + "; Initial Catalog = " + txtDatabase);
                myCommand.Parameters.Add(dsConnectionString);
            }
            CommandParameter dsUserName = new CommandParameter("username", txtUserName);

            myCommand.Parameters.Add(dsUserName);
            CommandParameter dsPassword = new CommandParameter("password", txtPassword);

            myCommand.Parameters.Add(dsPassword);
            CommandParameter dsExtension = new CommandParameter("Extension", "SQL");

            myCommand.Parameters.Add(dsExtension);
            string passwordString = "iLynq123";

            // create credential variable for connection to ssrs server
            System.Security.SecureString password = new System.Security.SecureString();
            for (int i = 0; i < passwordString.Length; i++)
            {
                password.AppendChar(passwordString[i]);
            }
            password.MakeReadOnly();
            PSCredential     Credential    = new PSCredential("iLynq", password);
            CommandParameter dsCredentials = new CommandParameter("credentials", Credential);

            myCommand.Parameters.Add(dsCredentials);

            Pipeline pipeline1 = runspace.CreatePipeline();

            pipeline1.Commands.Add(myCommand);
            try
            {
                pipeline1.Invoke();
            }
            catch (System.Management.Automation.CmdletInvocationException ex)
            {
                MessageBox.Show("Ivalid URL format", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            // close the runspace
            runspace.Close();
        }
Ejemplo n.º 35
0
        public void NewCommandInvalidInput()
        {
            // Build test variables for later
            var Con     = new SqlConnection(ConStr);
            var Con2    = new SqlConnection(ConStr2);
            var Params  = new SqlCommand().Parameters;
            var Params2 = new List <SqlParameter>();

            for (int i = 0; i < 3; i++)
            {
                Params.AddWithValue('@' + i.ToString(), i);
                Params2.Add(new SqlParameter('@' + i.ToString(), i + 1));
            }
            // Create fake credentials to test with
            var Cipher = new System.Security.SecureString();

            foreach (char c in Pwd)
            {
                Cipher.AppendChar(c);
            }

            // Test the attempt to create without ReadOnly password
            try
            {
                SqlCmd.New(Command2, ConStr2, UsrNm, Cipher);
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("password must be marked as read only.", ae.Message);
            }
            catch { Assert.Fail(); }

            // Make ReadOnly and continue testing
            Cipher.MakeReadOnly();
            var Cred = new SqlCredential(UsrNm, Cipher);

            // Test the attempt to create with IntegratedSecurity = True and Credentials
            try
            {
                SqlCmd.New(Command2, ConStr, Cred);
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("Cannot use Credential with Integrated Security connection string keyword.", ae.Message);
            }
            catch { Assert.Fail(); }

            // Test the attempt to create with null Credentials
            try
            {
                SqlCmd.New(Command2, ConStr2, null, "");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("Value cannot be null.\r\nParameter name: userId", ae.Message);
            }
            catch { Assert.Fail(); }
            try
            {
                SqlCmd.New(Command2, ConStr2, null, new System.Security.SecureString());
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("Value cannot be null.\r\nParameter name: userId", ae.Message);
            }
            catch { Assert.Fail(); }
        }
Ejemplo n.º 36
0
        public void NewCommandValidInput()
        {
            // Build test variables for later
            var Con     = new SqlConnection(ConStr);
            var Con2    = new SqlConnection(ConStr2);
            var Params  = new SqlCommand().Parameters;
            var Params2 = new List <SqlParameter>();

            for (int i = 0; i < 3; i++)
            {
                Params.AddWithValue('@' + i.ToString(), i);
                Params2.Add(new SqlParameter('@' + i.ToString(), i + 1));
            }
            // Create fake credentials to test with
            var Cipher = new System.Security.SecureString();

            foreach (char c in Pwd)
            {
                Cipher.AppendChar(c);
            }
            Cipher.MakeReadOnly();
            var Cred = new SqlCredential(UsrNm, Cipher);

            // Test1 - CommandText
            var Cmd = SqlCmd.New(Command);

            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.IsNull(Cmd.Connection);
            Cmd = null;

            // Test2 - CommandText, CommandType
            Cmd = SqlCmd.New(Command, CommandType.Text);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.AreEqual(CommandType.Text, Cmd.CommandType);
            Assert.IsNull(Cmd.Connection);
            Cmd = null;

            // Test3 - CommandText, Timeout
            Cmd = SqlCmd.New(Command, 3);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.AreEqual(3, Cmd.CommandTimeout);
            Assert.IsNull(Cmd.Connection);
            Cmd = null;

            // Test4 - CommandText, SqlConnection
            Cmd = SqlCmd.New(Command, Con);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.IsNotNull(Cmd.Connection);
            Assert.AreEqual(Con, Cmd.Connection);
            Cmd = null;

            // Test5 - CommandText, SqlParameterCollection
            Cmd = SqlCmd.New(Command3, Params);
            Assert.AreEqual(Command3, Cmd.CommandText);
            Assert.IsNotNull(Cmd.Parameters);
            for (int i = 0, j = Cmd.Parameters.Count; i < j; i++)
            {
                Assert.AreEqual(Params[i].ParameterName, Cmd.Parameters[i].ParameterName);
                Assert.AreEqual(Params[i].Value, Cmd.Parameters[i].Value);
            }
            Cmd = null;

            // Test6 - CommandText, ConnectionString
            Cmd = SqlCmd.New(Command, ConStr);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.IsNotNull(Cmd.Connection);
            Assert.AreEqual(ConStr, Cmd.Connection.ConnectionString);
            Cmd = null;

            // Test7 - CommandText, List<SqlParameter>
            Cmd = SqlCmd.New(Command3, Params2);
            Assert.AreEqual(Command3, Cmd.CommandText);
            for (int i = 0, j = Cmd.Parameters.Count; i < j; i++)
            {
                Assert.AreEqual(Params2[i].ParameterName, Cmd.Parameters[i].ParameterName);
                Assert.AreEqual(Params2[i].Value, Cmd.Parameters[i].Value);
            }

            // Test17 - CommandText, ConnectionString, SqlCredential
            Cmd = SqlCmd.New(Command2, ConStr2, Cred);
            Assert.AreEqual(Command2, Cmd.CommandText);
            Assert.IsNotNull(Cmd.Connection);
            Assert.IsNotNull(Cmd.Connection.Credential);
            Assert.AreEqual(ConStr2, Cmd.Connection.ConnectionString);
            Assert.AreEqual(Cred, Cmd.Connection.Credential);
            Cmd = null;

            // Test20 - CommandText, CommandType, Timeout, SqlParameterCollection
            Cmd = SqlCmd.New(Command3, CommandType.StoredProcedure, 15, Params);
            Assert.AreEqual(Command3, Cmd.CommandText);
            Assert.AreEqual(CommandType.StoredProcedure, Cmd.CommandType);
            Assert.AreEqual(15, Cmd.CommandTimeout);
            for (int i = 0, j = Cmd.Parameters.Count; i < j; i++)
            {
                Assert.AreEqual(Params[i].ParameterName, Cmd.Parameters[i].ParameterName);
                Assert.AreEqual(Params[i].Value, Cmd.Parameters[i].Value);
            }
            Cmd = null;

            // Test32 - CommandText, ConnectionString, Username, Password
            Cmd = SqlCmd.New(Command, ConStr2, UsrNm, Pwd);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.IsNotNull(Cmd.Connection);
            Assert.IsNotNull(Cmd.Connection.Credential);
            Assert.AreEqual(ConStr2, Cmd.Connection.ConnectionString);
            Assert.AreEqual(UsrNm, Cmd.Connection.Credential.UserId);
            Assert.AreEqual(8, Cmd.Connection.Credential.Password.Length);
            Cmd = null;

            // Test50 - CommandText, ConnectionString, SqlCredentail, CommandType, Timeout, List<SqlParameter>
            Cmd = SqlCmd.New(Command, ConStr2, Cred, CommandType.Text, 30, Params2);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.AreEqual(CommandType.Text, Cmd.CommandType);
            Assert.IsNotNull(Cmd.Connection);
            Assert.IsNotNull(Cmd.Connection.Credential);
            Assert.AreEqual(ConStr2, Cmd.Connection.ConnectionString);
            Assert.AreEqual(Cred, Cmd.Connection.Credential);
            Assert.AreEqual(30, Cmd.CommandTimeout);
            for (int i = 0, j = Cmd.Parameters.Count; i < j; i++)
            {
                Assert.AreEqual(Params2[i].ParameterName, Cmd.Parameters[i].ParameterName);
                Assert.AreEqual(Params2[i].Value, Cmd.Parameters[i].Value);
            }
            Cmd = null;

            // Test57 - CommandText, ConnectionString, Username, Password, CommandType, Timeout, List<SqlParameter>
            Cmd = SqlCmd.New(Command, ConStr2, UsrNm, Pwd, CommandType.Text, 120, Params2);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.AreEqual(CommandType.Text, Cmd.CommandType);
            Assert.IsNotNull(Cmd.Connection);
            Assert.IsNotNull(Cmd.Connection.Credential);
            Assert.AreEqual(ConStr2, Cmd.Connection.ConnectionString);
            Assert.AreEqual(UsrNm, Cmd.Connection.Credential.UserId);
            Assert.AreEqual(8, Cmd.Connection.Credential.Password.Length);
            Assert.AreEqual(120, Cmd.CommandTimeout);
            for (int i = 0, j = Cmd.Parameters.Count; i < j; i++)
            {
                Assert.AreEqual(Params2[i].ParameterName, Cmd.Parameters[i].ParameterName);
                Assert.AreEqual(Params2[i].Value, Cmd.Parameters[i].Value);
            }
            Cmd = null;
        }
Ejemplo n.º 37
0
 public static System.Security.SecureString SecureString(string pass)
 {
     System.Security.SecureString SSpass = new System.Security.SecureString();
     foreach (char c in pass)
     {
         SSpass.AppendChar(c);
     }
     SSpass.MakeReadOnly();
     return SSpass;
 }
Ejemplo n.º 38
0
 public System.Security.SecureString DecryptToSecureStringFromBase64(string inString)
 {
     byte[] bytes = Convert.FromBase64String(inString);
     bytes = Decrypt(bytes);
     System.Security.SecureString ret = new System.Security.SecureString();
     for (int i = 0; i < bytes.Length; i+=2)
     {
         ret.AppendChar( (char)(bytes[i]*256 + bytes[i+1]));
         bytes[i] = bytes[i+1] = 0;
     }
     ret.MakeReadOnly();
     return ret;
 }
Ejemplo n.º 39
0
 public EncryptedString(byte[] key)
 {
     str = new System.Security.SecureString();
     str.MakeReadOnly();
     encr = new EncryptionHelper(key);
 }