示例#1
0
 public Config()
     : base()
 {
     CloudFlareAPIKey = "";
     CloudFlareEmailAddress = "";
     LogToDisk = false;
     EmailAlertIPChange = true;
     EmailAlertNewVersion = true;
     EmailAlertUpdateError = true;
     EmailFrom = "";
     EmailTo = "";
     GetExternalIPMethodOrder = new GetExternalIPv4Methods[] { GetExternalIPv4Methods.UnicastAddress,
                                                               GetExternalIPv4Methods.NatPmp,
                                                               GetExternalIPv4Methods.Upnp,
                                                               GetExternalIPv4Methods.Http8880,
                                                               GetExternalIPv4Methods.Http80 };
     LastIPAddress = IPAddress.None.ToString();
     PointAPIKey = "";
     PointEmailAddress = "";
     SmtpHostname = "";
     SmtpPassword = new RMSecureString();
     SmtpPort = 587;
     SmtpSsl = true;
     SmtpUsername = "";
     if (!Load()) Save(); // Load (and save default config if not found)
 }
示例#2
0
        /// <summary>
        /// Create an instance of the ConfigurationHelper with a specific location and filename for the INI
        /// </summary>
        /// <remarks>
        /// The INI will be stored in the given location with the given name.  If the Global or User Application Data folder is selected, the INI will be created in the Application.CompanyName subdirectory.
        /// </remarks>
        protected ConfigHelper(ConfigSaveLocation saveLocation, string fileName)
        {
            SectionName = "CONFIGURATION";

            IniPassword            = new RMSecureString();
            Loaded                 = false;
            RMSecureStringPassword = new RMSecureString();

            switch (saveLocation)
            {
            case ConfigSaveLocation.Absolute:
                FileName = fileName;
                break;

            case ConfigSaveLocation.GlobalApplicationData:
                FileName = StringUtils.PathCombine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), ProcessUtils.CompanyName, fileName);
                break;

            case ConfigSaveLocation.Relative:
                FileName = StringUtils.PathCombine(ProcessUtils.StartupPath, fileName);
                break;

            case ConfigSaveLocation.UserApplicationData:
                FileName = StringUtils.PathCombine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ProcessUtils.CompanyName, fileName);
                break;
            }
        }
示例#3
0
        /// <summary>
        /// Hash the current SecureString with the SHA512 hash algorithm and saltBytes, returning the computed value as a base64 string
        /// </summary>
        /// <param name="saltBytes">The salt to apply to the hash</param>
        /// <returns>A base64 encoded hash of the current SecureString</returns>
        /// <remarks>Based on the code from Sly Gryphon's comment at http://weblogs.asp.net/pglavich/archive/2006/10/29/Secure-TextBox-Updated.aspx </remarks>
        public string GetHashedString(byte[] saltBytes)
        {
            string Result          = "";
            IntPtr secureStringPtr = IntPtr.Zero;

            try
            {
                // Get the secure string into a memory buffer
                if (_SecureStringSupported)
                {
                    secureStringPtr = Marshal.SecureStringToGlobalAllocAnsi((SecureString)_SecureString);
                }
                else
                {
                    secureStringPtr = Marshal.StringToHGlobalAnsi(((StringBuilder)_SecureString).ToString());
                }
                int stringSize = (saltBytes.Length + this.Length) * sizeof(byte);

                // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                unsafe
                {
                    byte[] fixedByteArray = new byte[stringSize];
                    fixed(byte *ptr = fixedByteArray)
                    {
                        try
                        {
                            // Add the salt bytes
                            for (int i = 0; i < saltBytes.Length; i++)
                            {
                                fixedByteArray[i] = saltBytes[i];
                            }

                            Marshal.Copy(secureStringPtr, fixedByteArray, saltBytes.Length, this.Length * sizeof(byte));

                            // Compute the hash
                            using (SHA512Managed SHA = new SHA512Managed())
                            {
                                Result = Convert.ToBase64String(SHA.ComputeHash(fixedByteArray));
                            }
                        }
                        finally
                        {
                            // Ensure managed array is cleared
                            Array.Clear(fixedByteArray, 0, stringSize);
                        }
                    }
                }
            }
            finally
            {
                // Ensure unmanaged memory is released.
                if (secureStringPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(secureStringPtr);
                }
            }

            return(Result);
        }
示例#4
0
        public static void Send(string smtp, int port, MailAddress from, MailAddress to, MailAddress sender, string subject, string body, string userName, RMSecureString password, bool ssl)
        {
            body = "<div style='background-color: #cccccc;'><h1>Error Message</h1>" + body + "</div>\r\n";

            body += AddCollection("QueryString", HttpContext.Current.Request.QueryString);
            body += AddCollection("Form", HttpContext.Current.Request.Form);
            body += AddCollection("Cookies", HttpContext.Current.Request.Cookies);
            body += AddCollection("Session", HttpContext.Current.Session);
            body += AddCollection("ServerVariables", HttpContext.Current.Request.ServerVariables);

            WebUtils.Email(smtp, port, from, to, sender, subject, body, true, userName, password, ssl);
        }
示例#5
0
 protected void ChangePassword(RMSecureString newPassword)
 {
     if (IniPassword.Length > 0)
     {
         if (!Loaded)
         {
             Load();
         }
         IniPassword = newPassword;
         Save();
     }
 }
示例#6
0
文件: WebUtils.cs 项目: Robin--/RMLib
        static public bool FtpUpload(bool useSsl, string hostName, string userName, RMSecureString password, string remoteDirectory, string fileName, EventHandler <FtpUploadProgressEventArgs> progressEventHandler)
        {
            FtpWebRequest ftpRequest = null;

            try
            {
                ftpRequest             = (FtpWebRequest)WebRequest.Create("ftp://" + hostName + remoteDirectory + Path.GetFileName(fileName));
                ftpRequest.Method      = WebRequestMethods.Ftp.UploadFile;
                ftpRequest.Proxy       = null;
                ftpRequest.UseBinary   = true;
                ftpRequest.UsePassive  = true;
                ftpRequest.Credentials = new NetworkCredential(userName, password.GetPlainText());
                ftpRequest.KeepAlive   = false;
                //ftpRequest.EnableSsl = ASSL;
                //if (ASSL) ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(FtpUploadCertificateValidation);

                FileInfo FI = new FileInfo(fileName);
                using (Stream Reader = FI.OpenRead())
                {
                    using (Stream Writer = ftpRequest.GetRequestStream())
                    {
                        FtpUploadProgressEventArgs e = new FtpUploadProgressEventArgs(FI.Length);
                        byte[] Buffer         = new byte[8192];
                        long   TotalBytesRead = 0;

                        progressEventHandler(null, e);
                        int BytesRead = Reader.Read(Buffer, 0, Buffer.Length);
                        while (BytesRead > 0)
                        {
                            TotalBytesRead += BytesRead;

                            Writer.Write(Buffer, 0, BytesRead);
                            e.BytesSent = TotalBytesRead;
                            progressEventHandler(null, e);

                            BytesRead = Reader.Read(Buffer, 0, Buffer.Length);
                        }
                    }
                }
                ftpRequest.GetResponse().Close();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                ftpRequest = null;
            }
        }
示例#7
0
文件: WebUtils.cs 项目: Robin--/RMLib
        public static bool FtpUpload(bool useSsl, string hostName, string userName, RMSecureString password, string remoteDirectory, string fileName, EventHandler<FtpUploadProgressEventArgs> progressEventHandler)
        {
            FtpWebRequest ftpRequest = null;
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + hostName + remoteDirectory + Path.GetFileName(fileName));
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
                ftpRequest.Proxy = null;
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.Credentials = new NetworkCredential(userName, password.GetPlainText());
                ftpRequest.KeepAlive = false;
                //ftpRequest.EnableSsl = ASSL;
                //if (ASSL) ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(FtpUploadCertificateValidation);

                FileInfo FI = new FileInfo(fileName);
                using (Stream Reader = FI.OpenRead())
                {
                    using (Stream Writer = ftpRequest.GetRequestStream())
                    {
                        FtpUploadProgressEventArgs e = new FtpUploadProgressEventArgs(FI.Length);
                        byte[] Buffer = new byte[8192];
                        long TotalBytesRead = 0;

                        progressEventHandler(null, e);
                        int BytesRead = Reader.Read(Buffer, 0, Buffer.Length);
                        while (BytesRead > 0)
                        {
                            TotalBytesRead += BytesRead;

                            Writer.Write(Buffer, 0, BytesRead);
                            e.BytesSent = TotalBytesRead;
                            progressEventHandler(null, e);

                            BytesRead = Reader.Read(Buffer, 0, Buffer.Length);
                        }
                    }
                }
                ftpRequest.GetResponse().Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                ftpRequest = null;
            }
        }
示例#8
0
文件: WebUtils.cs 项目: Robin--/RMLib
        public static void Email(string smtpHostname, int smtpPort, MailAddress fromAddress, MailAddress toAddress, MailAddress senderAddress, string subject, string body, bool isBodyHtml, string smtpUsername, RMSecureString smtpPassword, bool ssl)
        {
            MailMessage Msg = new MailMessage(fromAddress, toAddress);
            Msg.Sender = senderAddress;
            Msg.Subject = subject;
            Msg.Body = body;
            Msg.IsBodyHtml = isBodyHtml;

            SmtpClient Smtp = new SmtpClient(smtpHostname);
            if ((smtpUsername.Length > 0) && (smtpPassword.Length > 0))
            {
                Smtp.UseDefaultCredentials = false;
                Smtp.Credentials = new NetworkCredential(smtpUsername, smtpPassword.GetPlainText());
            }
            Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            Smtp.EnableSsl = ssl;
            Smtp.Port = smtpPort;
            Smtp.Timeout = 10000;
            Smtp.Send(Msg);
        }
示例#9
0
文件: WebUtils.cs 项目: Robin--/RMLib
        public static void Email(string smtpHostname, int smtpPort, MailAddress fromAddress, MailAddress toAddress, MailAddress senderAddress, string subject, string body, bool isBodyHtml, string smtpUsername, RMSecureString smtpPassword, bool ssl)
        {
            MailMessage Msg = new MailMessage(fromAddress, toAddress);

            Msg.Sender     = senderAddress;
            Msg.Subject    = subject;
            Msg.Body       = body;
            Msg.IsBodyHtml = isBodyHtml;

            SmtpClient Smtp = new SmtpClient(smtpHostname);

            if ((smtpUsername.Length > 0) && (smtpPassword.Length > 0))
            {
                Smtp.UseDefaultCredentials = false;
                Smtp.Credentials           = new NetworkCredential(smtpUsername, smtpPassword.GetPlainText());
            }
            Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            Smtp.EnableSsl      = ssl;
            Smtp.Port           = smtpPort;
            Smtp.Timeout        = 10000;
            Smtp.Send(Msg);
        }
示例#10
0
        /// <summary>
        /// Advanced load method that allows you to specify the section to read from
        /// </summary>
        /// <param name="sectionName">The section to read within the INI</param>
        /// <returns>true if the INI section existed; false otherwise</returns>
        protected bool Load(string sectionName)
        {
            // Store the section name
            SectionName = sectionName;

            // Load the application ini
            using (IniFile Ini = new IniFile(FileName, IniPassword))
            {

                // Check if the desired section exists
                if (!Ini.SectionExists(sectionName))
                {
                    // Nope, so abort
                    return false;
                }

                // Loop through each field in the inherited class and read the value from the Ini
                PropertyInfo[] Properties = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
                foreach (PropertyInfo Property in Properties)
                {
                    // Ensure we only look at read+write properties (read only helper properties should not be loaded from/saved to an ini)
                    if ((Property.CanRead) && (Property.CanWrite))
                    {
                        switch (Property.PropertyType.Name)
                        {
                            case "Boolean": Property.SetValue(this, Ini.ReadBoolean(sectionName, Property.Name, (Boolean)Property.GetValue(this, null)), null); break;
                            case "Boolean[]": Property.SetValue(this, Ini.ReadBoolean(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "Byte": Property.SetValue(this, Ini.ReadByte(sectionName, Property.Name, (Byte)Property.GetValue(this, null)), null); break;
                            case "Byte[]": Property.SetValue(this, Ini.ReadByte(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "Char": Property.SetValue(this, Ini.ReadChar(sectionName, Property.Name, (Char)Property.GetValue(this, null)), null); break;
                            case "Char[]": Property.SetValue(this, Ini.ReadChar(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "DateTime": Property.SetValue(this, Ini.ReadDateTime(sectionName, Property.Name, (DateTime)Property.GetValue(this, null)), null); break;
                            case "DateTime[]": Property.SetValue(this, Ini.ReadDateTime(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "Decimal": Property.SetValue(this, Ini.ReadDecimal(sectionName, Property.Name, (Decimal)Property.GetValue(this, null)), null); break;
                            case "Decimal[]": Property.SetValue(this, Ini.ReadDecimal(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "Double": Property.SetValue(this, Ini.ReadDouble(sectionName, Property.Name, (Double)Property.GetValue(this, null)), null); break;
                            case "Double[]": Property.SetValue(this, Ini.ReadDouble(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "Int16": Property.SetValue(this, Ini.ReadInt16(sectionName, Property.Name, (Int16)Property.GetValue(this, null)), null); break;
                            case "Int16[]": Property.SetValue(this, Ini.ReadInt16(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "Int32": Property.SetValue(this, Ini.ReadInt32(sectionName, Property.Name, (Int32)Property.GetValue(this, null)), null); break;
                            case "Int32[]": Property.SetValue(this, Ini.ReadInt32(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "Int64": Property.SetValue(this, Ini.ReadInt64(sectionName, Property.Name, (Int64)Property.GetValue(this, null)), null); break;
                            case "Int64[]": Property.SetValue(this, Ini.ReadInt64(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "SByte": Property.SetValue(this, Ini.ReadSByte(sectionName, Property.Name, (SByte)Property.GetValue(this, null)), null); break;
                            case "SByte[]": Property.SetValue(this, Ini.ReadSByte(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "Single": Property.SetValue(this, Ini.ReadSingle(sectionName, Property.Name, (Single)Property.GetValue(this, null)), null); break;
                            case "Single[]": Property.SetValue(this, Ini.ReadSingle(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "String": Property.SetValue(this, Ini.ReadString(sectionName, Property.Name, Property.GetValue(this, null).ToString()), null); break;
                            case "String[]": Property.SetValue(this, Ini.ReadString(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "UInt16": Property.SetValue(this, Ini.ReadUInt16(sectionName, Property.Name, (UInt16)Property.GetValue(this, null)), null); break;
                            case "UInt16[]": Property.SetValue(this, Ini.ReadUInt16(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "UInt32": Property.SetValue(this, Ini.ReadUInt32(sectionName, Property.Name, (UInt32)Property.GetValue(this, null)), null); break;
                            case "UInt32[]": Property.SetValue(this, Ini.ReadUInt32(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "UInt64": Property.SetValue(this, Ini.ReadUInt64(sectionName, Property.Name, (UInt64)Property.GetValue(this, null)), null); break;
                            case "UInt64[]": Property.SetValue(this, Ini.ReadUInt64(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;
                            case "RMSecureString":
                                string Enc = Ini.ReadString(sectionName, Property.Name, "");
                                if (Enc.Length > 0)
                                {
                                    RMSecureString RMSS = new RMSecureString();
                                    try
                                    {
                                        if (RMSecureStringPassword.Length == 0)
                                        {
                                            // No password means protected string
                                            RMSS.LoadFromProtectedString(Enc, RMSecureStringPassword);
                                        }
                                        else
                                        {
                                            // Password means encrypted string
                                            RMSS.LoadFromEncryptedString(Enc, RMSecureStringPassword);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        // Loading failed -- could be that the protection happened under a different user account, or the password is incorrect
                                        // TODO Should really save the exception and throw it later I think
                                        RMSS = new RMSecureString();
                                    }
                                    Property.SetValue(this, RMSS, null);
                                }
                                break;
                            case "StringDictionary":
                                StringDictionary SD = new StringDictionary();

                                string[] Keys = Ini.ReadSection(sectionName);
                                foreach (string Key in Keys)
                                {
                                    if (Key.IndexOf(Property.Name + "_", StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        string KeyWithoutPrefix = Key.Substring(Property.Name.Length + 1);
                                        SD.Add(KeyWithoutPrefix, Ini.ReadString(sectionName, Key, ""));
                                    }
                                }

                                Property.SetValue(this, SD, null);
                                //string Section = Property.Name.ToUpper();
                                //string[] Keys = Ini.ReadSection(Section);

                                //StringDictionary SD = new StringDictionary();
                                //foreach (string Key in Keys)
                                //{
                                //    SD.Add(Key, Ini.ReadString(Section, Key, ""));
                                //}
                                //Property.SetValue(this, SD, null);
                                break;
                            default:
                                // Check for enum, which we can try to parse
                                if (Property.PropertyType.BaseType.Name == "Array")
                                {
                                    List<int> EnumValues = new List<int>();
                                    string[] StringValues = Ini.ReadString(sectionName, Property.Name, (IList)Property.GetValue(this, null));
                                    foreach (string StringValue in StringValues)
                                    {
                                        EnumValues.Add((int)Enum.Parse(Property.PropertyType.GetElementType(), StringValue));
                                    }
                                    Property.SetValue(this, EnumValues.ToArray(), null);
                                }
                                else if (Property.PropertyType.BaseType.Name == "Enum")
                                {
                                    Property.SetValue(this, Enum.Parse(Property.PropertyType, Ini.ReadString(sectionName, Property.Name, Property.GetValue(this, null).ToString())), null);
                                }
                                break;
                        }
                    }
                }
            }

            Loaded = true;
            return true;
        }
示例#11
0
 protected void ChangePassword(RMSecureString newPassword)
 {
     if (IniPassword.Length > 0)
     {
         if (!Loaded) Load();
         IniPassword = newPassword;
         Save();
     }
 }
示例#12
0
        public void LoadFromProtectedString(string protectedString, RMSecureString password)
        {
            Clear();

            if (protectedString.StartsWith("e"))
            {
                LoadFromEncryptedString(protectedString, password);
            }
            else if (protectedString.StartsWith("p"))
            {
                // Trim leading 'p', which is just an indicator to say that this is an encrypted and not a protected string
                protectedString = protectedString.Substring(1);

                IntPtr PasswordPtr = IntPtr.Zero;

                try
                {
                    // Get the secure password string into a memory buffer
                    PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                    int PasswordSize = password.Length * sizeof(byte);

                    // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                    unsafe
                    {
                        byte[] Decrypted = null;
                        byte[] PasswordBytes = new byte[PasswordSize];
                        fixed (byte* ptr = PasswordBytes)
                        {
                            try
                            {
                                Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                                if (PasswordSize == 0)
                                {
                                    Decrypted = ProtectedData.Unprotect(Convert.FromBase64String(protectedString), null, DataProtectionScope.CurrentUser);
                                }
                                else
                                {
                                    Decrypted = ProtectedData.Unprotect(Convert.FromBase64String(protectedString), PasswordBytes, DataProtectionScope.CurrentUser);
                                }

                                for (int i = 0; i < Decrypted.Length; i++)
                                {
                                    if (_SecureStringSupported)
                                    {
                                        ((SecureString)_SecureString).AppendChar((char)Decrypted[i]);
                                    }
                                    else
                                    {
                                        ((StringBuilder)_SecureString).Append((char)Decrypted[i]);
                                    }
                                }
                            }
                            finally
                            {
                                // Ensure managed array is cleared
                                if (Decrypted != null) Array.Clear(Decrypted, 0, Decrypted.Length);
                                Array.Clear(PasswordBytes, 0, PasswordSize);
                            }
                        }
                    }
                }
                finally
                {
                    // Ensure unmanaged memory is released.
                    if (PasswordPtr != IntPtr.Zero)
                    {
                        Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                    }
                }
            }
        }
示例#13
0
        public string GetEncryptedString(RMSecureString password)
        {
            string Result = "";

            IntPtr PlainTextPtr = IntPtr.Zero;
            IntPtr PasswordPtr  = IntPtr.Zero;

            try
            {
                // Get the secure plaintext string into a memory buffer
                if (_SecureStringSupported)
                {
                    PlainTextPtr = Marshal.SecureStringToGlobalAllocAnsi((SecureString)_SecureString);
                }
                else
                {
                    PlainTextPtr = Marshal.StringToHGlobalAnsi(((StringBuilder)_SecureString).ToString());
                }
                int PlainTextSize = this.Length * sizeof(byte);

                // Get the secure password string into a memory buffer
                PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                int PasswordSize = password.Length * sizeof(byte);

                // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                unsafe
                {
                    byte[] PlainTextBytes = new byte[PlainTextSize];
                    fixed(byte *ptr1 = PlainTextBytes)
                    {
                        byte[] PasswordBytes = new byte[PasswordSize];
                        fixed(byte *ptr2 = PasswordBytes)
                        {
                            try
                            {
                                Marshal.Copy(PlainTextPtr, PlainTextBytes, 0, PlainTextSize);
                                Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                                PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(PasswordBytes, Encoding.ASCII.GetBytes("RMSecureString"), "SHA512", 12345);
                                using (RijndaelManaged SymmetricKey = new RijndaelManaged())
                                {
                                    SymmetricKey.Mode = CipherMode.CBC;
                                    using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(DerivedPassword.GetBytes(32), DerivedPassword.GetBytes(16)))
                                    {
                                        using (MemoryStream MemStream = new MemoryStream())
                                        {
                                            using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                                            {
                                                CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                                                CryptoStream.FlushFinalBlock();

                                                Result = "e" + Convert.ToBase64String(MemStream.ToArray());
                                            }
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                // Ensure managed array is cleared
                                Array.Clear(PlainTextBytes, 0, PlainTextSize);

                                // Ensure managed array is cleared
                                Array.Clear(PasswordBytes, 0, PasswordSize);
                            }
                        }
                    }
                }
            }
            finally
            {
                // Ensure unmanaged memory is released.
                if (PlainTextPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PlainTextPtr);
                }

                // Ensure unmanaged memory is released.
                if (PasswordPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                }
            }

            return(Result);
        }
示例#14
0
        /// <summary>
        /// Encrypt the current SecureString with the ProtectData API, returning the computed value as a base64 string
        /// </summary>
        /// <returns>A base64 encoded string of the protected version of the current SecureString</returns>
        /// <remarks>Based on the code from Sly Gryphon's comment at http://weblogs.asp.net/pglavich/archive/2006/10/29/Secure-TextBox-Updated.aspx </remarks>
        public string GetProtectedString(RMSecureString password)
        {
            string Result = "";

            IntPtr PlainTextPtr = IntPtr.Zero;
            IntPtr PasswordPtr  = IntPtr.Zero;

            try
            {
                // Get the secure plaintext string into a memory buffer
                if (_SecureStringSupported)
                {
                    PlainTextPtr = Marshal.SecureStringToGlobalAllocAnsi((SecureString)_SecureString);
                }
                else
                {
                    PlainTextPtr = Marshal.StringToHGlobalAnsi(((StringBuilder)_SecureString).ToString());
                }
                int PlainTextSize = this.Length * sizeof(byte);

                // Get the secure password string into a memory buffer
                PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                int PasswordSize = password.Length * sizeof(byte);

                // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                unsafe
                {
                    byte[] PlainTextBytes = new byte[PlainTextSize];
                    fixed(byte *ptr1 = PlainTextBytes)
                    {
                        byte[] PasswordBytes = new byte[PasswordSize];
                        fixed(byte *ptr2 = PasswordBytes)
                        {
                            try
                            {
                                Marshal.Copy(PlainTextPtr, PlainTextBytes, 0, PlainTextSize);
                                Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                                if (PasswordSize == 0)
                                {
                                    Result = "p" + Convert.ToBase64String(ProtectedData.Protect(PlainTextBytes, null, DataProtectionScope.CurrentUser));
                                }
                                else
                                {
                                    Result = "p" + Convert.ToBase64String(ProtectedData.Protect(PlainTextBytes, PasswordBytes, DataProtectionScope.CurrentUser));
                                }
                            }
                            finally
                            {
                                // Ensure managed array is cleared
                                Array.Clear(PlainTextBytes, 0, PlainTextSize);

                                // Ensure managed array is cleared
                                Array.Clear(PasswordBytes, 0, PasswordSize);
                            }
                        }
                    }
                }
            }
            finally
            {
                // Ensure unmanaged memory is released.
                if (PlainTextPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PlainTextPtr);
                }

                // Ensure unmanaged memory is released.
                if (PasswordPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                }
            }

            return(Result);
        }
示例#15
0
        /// <summary>
        /// Custom constructor to load the given INI into memory, and indicate whether the changes should be buffered or immediately written to disk
        /// </summary>
        /// <param name="fileName">The INI to load</param>
        /// <param name="password">The password used to encrypt/decrypt the contents of the INI file</param>
        public IniFile(string fileName, RMSecureString password)
        {
            AutoSave = false;
            Password = new RMSecureString();

            _FileName = fileName;
            Password  = password;

            List <string> CurrentComment = new List <string>();
            string        CurrentSection = "";

            if (File.Exists(fileName))
            {
                // Read in the INI file
                string FileText = FileUtils.FileReadAllText(fileName, RMEncoding.Ansi);

                // Decrypt the INI file (if necessary)
                if (password.Length > 0)
                {
                    try
                    {
                        FileText = AES.Decrypt(FileText, password.GetPlainText(), INI_FILE_SALT);
                        Password = password;
                    }
                    catch (Exception)
                    {
                        return;
                    }
                }

                // Split the INI file into separate lines
                string[] Lines = FileText.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');

                // Loop through each line
                foreach (string Line in Lines)
                {
                    // Make sure the line isn't empty
                    if ((!string.IsNullOrEmpty(Line.Trim())))
                    {
                        // Check if this is a comment
                        if (Line.TrimStart().StartsWith(";"))
                        {
                            if (string.IsNullOrEmpty(CurrentSection))
                            {
                                _HeaderComment.Add(Line.TrimStart().Substring(1));
                            }
                            else
                            {
                                CurrentComment.Add(Line.TrimStart().Substring(1));
                            }
                        }
                        else
                        {
                            // Check if this is a new section
                            if ((Line.TrimStart().StartsWith("[")) && (Line.TrimEnd().EndsWith("]")))
                            {
                                // It is, so add the new section
                                CurrentSection            = Line.Trim().Substring(1, Line.Trim().Length - 2);
                                _Sections[CurrentSection] = new IniFileSection(CurrentComment);
                                _SectionNames.Add(CurrentSection);
                                CurrentComment = new List <string>();
                            }
                            else
                            {
                                // It isn't so add the key/value to the current section
                                if (!string.IsNullOrEmpty(CurrentSection))
                                {
                                    // Make sure this line is in the KEY=VALUE form
                                    int EqualPos = Line.IndexOf('=');
                                    if (EqualPos >= 1)
                                    {
                                        // Get the key
                                        string Key = Line.Substring(0, EqualPos);

                                        // Get the value
                                        string Value = Line.Substring(EqualPos + 1);

                                        // Add the key/value pair to the dictionary
                                        _Sections[CurrentSection].WriteString(CurrentComment, Key, Value);
                                        CurrentComment = new List <string>();
                                    }
                                }
                            }
                        }
                    }
                }

                // Ensure the supplied password is valid
                if (Password.Length > 0)
                {
                    if ((_HeaderComment.Count == 0) || (_HeaderComment[0] != INI_FILE_ENCRYPTED_HEADER))
                    {
                        // Password did not properly decrypt the ini file
                        _Sections.Clear();
                        _SectionNames.Clear();
                        return;
                    }
                }
            }
        }
示例#16
0
        private void LoadFromEncryptedStringv2(string encryptedString, RMSecureString password)
        {
            Clear();

            // encryptedString is in the format e!2!{iterations}!{base64:salt}!{base64:iv}!{base64:encrypted_password}, so split it
            string[] Pieces     = encryptedString.Split('!');
            int      Iterations = int.Parse(Pieces[2]);

            byte[] SaltBytes = Convert.FromBase64String(Pieces[3]);
            byte[] IVBytes   = Convert.FromBase64String(Pieces[4]);
            encryptedString = Pieces[5];

            IntPtr PasswordPtr = IntPtr.Zero;

            try {
                // Get the secure password string into a memory buffer
                PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                int PasswordSize = password.Length * sizeof(byte);

                // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                unsafe {
                    byte[] Decrypted     = null;
                    byte[] PasswordBytes = new byte[PasswordSize];
                    fixed(byte *ptr = PasswordBytes)
                    {
                        try {
                            Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                            var DerivedPassword = new Rfc2898DeriveBytes(PasswordBytes, SaltBytes, Iterations);
                            using (RijndaelManaged SymmetricKey = new RijndaelManaged()) {
                                SymmetricKey.IV   = IVBytes;
                                SymmetricKey.Key  = DerivedPassword.GetBytes(16);
                                SymmetricKey.Mode = CipherMode.CBC;
                                using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor()) {
                                    using (MemoryStream MemStream = new MemoryStream(Convert.FromBase64String(encryptedString))) {
                                        using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)) {
                                            byte[] DecryptedByte = new byte[1];

                                            int ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
                                            while (ByteCount > 0)
                                            {
                                                _SecureString.AppendChar((char)DecryptedByte[0]);
                                                ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
                                            }
                                        }
                                    }
                                }
                            }
                        } finally {
                            // Ensure managed array is cleared
                            if (Decrypted != null)
                            {
                                Array.Clear(Decrypted, 0, Decrypted.Length);
                            }
                            Array.Clear(PasswordBytes, 0, PasswordSize);
                        }
                    }
                }
            } finally {
                // Ensure unmanaged memory is released.
                if (PasswordPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                }
            }
        }
示例#17
0
        public string GetEncryptedString(RMSecureString password, int iterations = 32768)
        {
            string Result = "";

            IntPtr PlainTextPtr = IntPtr.Zero;
            IntPtr PasswordPtr  = IntPtr.Zero;

            try
            {
                // Get the secure plaintext string into a memory buffer
                PlainTextPtr = Marshal.SecureStringToGlobalAllocAnsi(_SecureString);
                int PlainTextSize = this.Length * sizeof(byte);

                // Get the secure password string into a memory buffer
                PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                int PasswordSize = password.Length * sizeof(byte);

                // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                unsafe
                {
                    byte[] PlainTextBytes = new byte[PlainTextSize];
                    fixed(byte *ptr1 = PlainTextBytes)
                    {
                        byte[] PasswordBytes = new byte[PasswordSize];
                        fixed(byte *ptr2 = PasswordBytes)
                        {
                            try
                            {
                                Marshal.Copy(PlainTextPtr, PlainTextBytes, 0, PlainTextSize);
                                Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                                // Get random bytes for salt
                                var    RNG       = new RNGCryptoServiceProvider();
                                byte[] SaltBytes = new byte[16];
                                RNG.GetBytes(SaltBytes);

                                // PBKDF2 key stretching
                                var DerivedPassword = new Rfc2898DeriveBytes(PasswordBytes, SaltBytes, iterations);

                                // Encryption with 128bit AES (using 192 or 256 bit isn't a good idea because Rfc2898DeriveBytes uses SHA-1, a 160 bit algorithm,
                                // so it's not recommended to take out more than 160 bits (increases time required to hash, but not time required to verify
                                // a hash, which means a defender does extra work but an attacker doesn't have to...Google it for reasons)
                                using (RijndaelManaged SymmetricKey = new RijndaelManaged()) {
                                    SymmetricKey.GenerateIV();
                                    SymmetricKey.Key  = DerivedPassword.GetBytes(16);
                                    SymmetricKey.Mode = CipherMode.CBC;
                                    using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor())
                                    {
                                        using (MemoryStream MemStream = new MemoryStream())
                                        {
                                            using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                                            {
                                                CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                                                CryptoStream.FlushFinalBlock();

                                                Result = $"e!2!{iterations}!{Convert.ToBase64String(SaltBytes)}!{Convert.ToBase64String(SymmetricKey.IV)}!{Convert.ToBase64String(MemStream.ToArray())}";
                                            }
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                // Ensure managed array is cleared
                                Array.Clear(PlainTextBytes, 0, PlainTextSize);

                                // Ensure managed array is cleared
                                Array.Clear(PasswordBytes, 0, PasswordSize);
                            }
                        }
                    }
                }
            }
            finally
            {
                // Ensure unmanaged memory is released.
                if (PlainTextPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PlainTextPtr);
                }

                // Ensure unmanaged memory is released.
                if (PasswordPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                }
            }

            return(Result);
        }
示例#18
0
        /// <summary>
        /// Encrypt the current SecureString with the ProtectData API, returning the computed value as a base64 string
        /// </summary>
        /// <returns>A base64 encoded string of the protected version of the current SecureString</returns>
        /// <remarks>Based on the code from Sly Gryphon's comment at http://weblogs.asp.net/pglavich/archive/2006/10/29/Secure-TextBox-Updated.aspx </remarks>
        public string GetProtectedString(RMSecureString password)
        {
            string Result = "";

            IntPtr PlainTextPtr = IntPtr.Zero;
            IntPtr PasswordPtr = IntPtr.Zero;

            try
            {
                // Get the secure plaintext string into a memory buffer
                if (_SecureStringSupported)
                {
                    PlainTextPtr = Marshal.SecureStringToGlobalAllocAnsi((SecureString)_SecureString);
                }
                else
                {
                    PlainTextPtr = Marshal.StringToHGlobalAnsi(((StringBuilder)_SecureString).ToString());
                }
                int PlainTextSize = this.Length * sizeof(byte);

                // Get the secure password string into a memory buffer
                PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                int PasswordSize = password.Length * sizeof(byte);

                // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                unsafe
                {
                    byte[] PlainTextBytes = new byte[PlainTextSize];
                    fixed (byte* ptr1 = PlainTextBytes)
                    {
                        byte[] PasswordBytes = new byte[PasswordSize];
                        fixed (byte* ptr2 = PasswordBytes)
                        {
                            try
                            {
                                Marshal.Copy(PlainTextPtr, PlainTextBytes, 0, PlainTextSize);
                                Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                                if (PasswordSize == 0)
                                {
                                    Result = "p" + Convert.ToBase64String(ProtectedData.Protect(PlainTextBytes, null, DataProtectionScope.CurrentUser));
                                }
                                else
                                {
                                    Result = "p" + Convert.ToBase64String(ProtectedData.Protect(PlainTextBytes, PasswordBytes, DataProtectionScope.CurrentUser));
                                }
                            }
                            finally
                            {
                                // Ensure managed array is cleared
                                Array.Clear(PlainTextBytes, 0, PlainTextSize);

                                // Ensure managed array is cleared
                                Array.Clear(PasswordBytes, 0, PasswordSize);
                            }
                        }
                    }
                }
            }
            finally
            {
                // Ensure unmanaged memory is released.
                if (PlainTextPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PlainTextPtr);
                }

                // Ensure unmanaged memory is released.
                if (PasswordPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                }
            }

            return Result;
        }
示例#19
0
        /// <summary>
        /// Advanced load method that allows you to specify the section to read from
        /// </summary>
        /// <param name="sectionName">The section to read within the INI</param>
        /// <returns>true if the INI section existed; false otherwise</returns>
        protected bool Load(string sectionName)
        {
            // Store the section name
            SectionName = sectionName;

            // Load the application ini
            using (IniFile Ini = new IniFile(FileName, IniPassword))
            {
                // Check if the desired section exists
                if (!Ini.SectionExists(sectionName))
                {
                    // Nope, so abort
                    return(false);
                }

                // Loop through each field in the inherited class and read the value from the Ini
                PropertyInfo[] Properties = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
                foreach (PropertyInfo Property in Properties)
                {
                    // Ensure we only look at read+write properties (read only helper properties should not be loaded from/saved to an ini)
                    if ((Property.CanRead) && (Property.CanWrite))
                    {
                        switch (Property.PropertyType.Name)
                        {
                        case "Boolean": Property.SetValue(this, Ini.ReadBoolean(sectionName, Property.Name, (Boolean)Property.GetValue(this, null)), null); break;

                        case "Boolean[]": Property.SetValue(this, Ini.ReadBoolean(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "Byte": Property.SetValue(this, Ini.ReadByte(sectionName, Property.Name, (Byte)Property.GetValue(this, null)), null); break;

                        case "Byte[]": Property.SetValue(this, Ini.ReadByte(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "Char": Property.SetValue(this, Ini.ReadChar(sectionName, Property.Name, (Char)Property.GetValue(this, null)), null); break;

                        case "Char[]": Property.SetValue(this, Ini.ReadChar(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "DateTime": Property.SetValue(this, Ini.ReadDateTime(sectionName, Property.Name, (DateTime)Property.GetValue(this, null)), null); break;

                        case "DateTime[]": Property.SetValue(this, Ini.ReadDateTime(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "Decimal": Property.SetValue(this, Ini.ReadDecimal(sectionName, Property.Name, (Decimal)Property.GetValue(this, null)), null); break;

                        case "Decimal[]": Property.SetValue(this, Ini.ReadDecimal(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "Double": Property.SetValue(this, Ini.ReadDouble(sectionName, Property.Name, (Double)Property.GetValue(this, null)), null); break;

                        case "Double[]": Property.SetValue(this, Ini.ReadDouble(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "Int16": Property.SetValue(this, Ini.ReadInt16(sectionName, Property.Name, (Int16)Property.GetValue(this, null)), null); break;

                        case "Int16[]": Property.SetValue(this, Ini.ReadInt16(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "Int32": Property.SetValue(this, Ini.ReadInt32(sectionName, Property.Name, (Int32)Property.GetValue(this, null)), null); break;

                        case "Int32[]": Property.SetValue(this, Ini.ReadInt32(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "Int64": Property.SetValue(this, Ini.ReadInt64(sectionName, Property.Name, (Int64)Property.GetValue(this, null)), null); break;

                        case "Int64[]": Property.SetValue(this, Ini.ReadInt64(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "SByte": Property.SetValue(this, Ini.ReadSByte(sectionName, Property.Name, (SByte)Property.GetValue(this, null)), null); break;

                        case "SByte[]": Property.SetValue(this, Ini.ReadSByte(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "Single": Property.SetValue(this, Ini.ReadSingle(sectionName, Property.Name, (Single)Property.GetValue(this, null)), null); break;

                        case "Single[]": Property.SetValue(this, Ini.ReadSingle(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "String": Property.SetValue(this, Ini.ReadString(sectionName, Property.Name, Property.GetValue(this, null).ToString()), null); break;

                        case "String[]": Property.SetValue(this, Ini.ReadString(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "UInt16": Property.SetValue(this, Ini.ReadUInt16(sectionName, Property.Name, (UInt16)Property.GetValue(this, null)), null); break;

                        case "UInt16[]": Property.SetValue(this, Ini.ReadUInt16(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "UInt32": Property.SetValue(this, Ini.ReadUInt32(sectionName, Property.Name, (UInt32)Property.GetValue(this, null)), null); break;

                        case "UInt32[]": Property.SetValue(this, Ini.ReadUInt32(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "UInt64": Property.SetValue(this, Ini.ReadUInt64(sectionName, Property.Name, (UInt64)Property.GetValue(this, null)), null); break;

                        case "UInt64[]": Property.SetValue(this, Ini.ReadUInt64(sectionName, Property.Name, (IList)Property.GetValue(this, null)), null); break;

                        case "RMSecureString":
                            string Enc = Ini.ReadString(sectionName, Property.Name, "");
                            if (Enc.Length > 0)
                            {
                                RMSecureString RMSS = new RMSecureString();
                                try
                                {
                                    if (RMSecureStringPassword.Length == 0)
                                    {
                                        // No password means protected string
                                        RMSS.LoadFromProtectedString(Enc, RMSecureStringPassword);
                                    }
                                    else
                                    {
                                        // Password means encrypted string
                                        RMSS.LoadFromEncryptedString(Enc, RMSecureStringPassword);
                                    }
                                }
                                catch (Exception)
                                {
                                    // Loading failed -- could be that the protection happened under a different user account, or the password is incorrect
                                    // TODO Should really save the exception and throw it later I think
                                    RMSS = new RMSecureString();
                                }
                                Property.SetValue(this, RMSS, null);
                            }
                            break;

                        case "StringDictionary":
                            StringDictionary SD = new StringDictionary();

                            string[] Keys = Ini.ReadSection(sectionName);
                            foreach (string Key in Keys)
                            {
                                if (Key.IndexOf(Property.Name + "_", StringComparison.OrdinalIgnoreCase) == 0)
                                {
                                    string KeyWithoutPrefix = Key.Substring(Property.Name.Length + 1);
                                    SD.Add(KeyWithoutPrefix, Ini.ReadString(sectionName, Key, ""));
                                }
                            }

                            Property.SetValue(this, SD, null);
                            //string Section = Property.Name.ToUpper();
                            //string[] Keys = Ini.ReadSection(Section);

                            //StringDictionary SD = new StringDictionary();
                            //foreach (string Key in Keys)
                            //{
                            //    SD.Add(Key, Ini.ReadString(Section, Key, ""));
                            //}
                            //Property.SetValue(this, SD, null);
                            break;

                        default:
                            // Check for enum, which we can try to parse
                            if (Property.PropertyType.BaseType.Name == "Array")
                            {
                                List <int> EnumValues   = new List <int>();
                                string[]   StringValues = Ini.ReadString(sectionName, Property.Name, (IList)Property.GetValue(this, null));
                                foreach (string StringValue in StringValues)
                                {
                                    EnumValues.Add((int)Enum.Parse(Property.PropertyType.GetElementType(), StringValue));
                                }
                                Property.SetValue(this, EnumValues.ToArray(), null);
                            }
                            else if (Property.PropertyType.BaseType.Name == "Enum")
                            {
                                Property.SetValue(this, Enum.Parse(Property.PropertyType, Ini.ReadString(sectionName, Property.Name, Property.GetValue(this, null).ToString())), null);
                            }
                            break;
                        }
                    }
                }
            }

            Loaded = true;
            return(true);
        }
示例#20
0
        /// <summary>
        /// Hash the current SecureString with the SHA512 hash algorithm and saltBytes, returning the computed value as a base64 string
        /// </summary>
        /// <param name="saltBytes">The salt to apply to the hash</param>
        /// <returns>A base64 encoded hash of the current SecureString</returns>
        /// <remarks>Based on the code from Sly Gryphon's comment at http://weblogs.asp.net/pglavich/archive/2006/10/29/Secure-TextBox-Updated.aspx </remarks>
        public string GetHashedString(byte[] saltBytes)
        {
            string Result = "";
            IntPtr secureStringPtr = IntPtr.Zero;

            try
            {
                // Get the secure string into a memory buffer
                if (_SecureStringSupported)
                {
                    secureStringPtr = Marshal.SecureStringToGlobalAllocAnsi((SecureString)_SecureString);
                }
                else
                {
                    secureStringPtr = Marshal.StringToHGlobalAnsi(((StringBuilder)_SecureString).ToString());
                }
                int stringSize = (saltBytes.Length + this.Length) * sizeof(byte);

                // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                unsafe
                {
                    byte[] fixedByteArray = new byte[stringSize];
                    fixed (byte* ptr = fixedByteArray)
                    {
                        try
                        {
                            // Add the salt bytes
                            for (int i = 0; i < saltBytes.Length; i++) fixedByteArray[i] = saltBytes[i];

                            Marshal.Copy(secureStringPtr, fixedByteArray, saltBytes.Length, this.Length * sizeof(byte));

                            // Compute the hash
                            using (SHA512Managed SHA = new SHA512Managed())
                            {
                                Result = Convert.ToBase64String(SHA.ComputeHash(fixedByteArray));
                            }
                        }
                        finally
                        {
                            // Ensure managed array is cleared
                            Array.Clear(fixedByteArray, 0, stringSize);
                        }
                    }
                }
            }
            finally
            {
                // Ensure unmanaged memory is released.
                if (secureStringPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(secureStringPtr);
                }
            }

            return Result;
        }
示例#21
0
        public void LoadFromProtectedString(string protectedString, RMSecureString password)
        {
            Clear();

            if (protectedString.StartsWith("e"))
            {
                LoadFromEncryptedString(protectedString, password);
            }
            else if (protectedString.StartsWith("p"))
            {
                // Trim leading 'p', which is just an indicator to say that this is an encrypted and not a protected string
                protectedString = protectedString.Substring(1);

                IntPtr PasswordPtr = IntPtr.Zero;

                try
                {
                    // Get the secure password string into a memory buffer
                    PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                    int PasswordSize = password.Length * sizeof(byte);

                    // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                    unsafe
                    {
                        byte[] Decrypted     = null;
                        byte[] PasswordBytes = new byte[PasswordSize];
                        fixed(byte *ptr = PasswordBytes)
                        {
                            try
                            {
                                Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                                if (PasswordSize == 0)
                                {
                                    Decrypted = ProtectedData.Unprotect(Convert.FromBase64String(protectedString), null, DataProtectionScope.CurrentUser);
                                }
                                else
                                {
                                    Decrypted = ProtectedData.Unprotect(Convert.FromBase64String(protectedString), PasswordBytes, DataProtectionScope.CurrentUser);
                                }

                                for (int i = 0; i < Decrypted.Length; i++)
                                {
                                    if (_SecureStringSupported)
                                    {
                                        ((SecureString)_SecureString).AppendChar((char)Decrypted[i]);
                                    }
                                    else
                                    {
                                        ((StringBuilder)_SecureString).Append((char)Decrypted[i]);
                                    }
                                }
                            }
                            finally
                            {
                                // Ensure managed array is cleared
                                if (Decrypted != null)
                                {
                                    Array.Clear(Decrypted, 0, Decrypted.Length);
                                }
                                Array.Clear(PasswordBytes, 0, PasswordSize);
                            }
                        }
                    }
                }
                finally
                {
                    // Ensure unmanaged memory is released.
                    if (PasswordPtr != IntPtr.Zero)
                    {
                        Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                    }
                }
            }
        }
示例#22
0
        public string GetEncryptedString(RMSecureString password)
        {
            string Result = "";

            IntPtr PlainTextPtr = IntPtr.Zero;
            IntPtr PasswordPtr = IntPtr.Zero;

            try
            {
                // Get the secure plaintext string into a memory buffer
                if (_SecureStringSupported)
                {
                    PlainTextPtr = Marshal.SecureStringToGlobalAllocAnsi((SecureString)_SecureString);
                }
                else
                {
                    PlainTextPtr = Marshal.StringToHGlobalAnsi(((StringBuilder)_SecureString).ToString());
                }
                int PlainTextSize = this.Length * sizeof(byte);

                // Get the secure password string into a memory buffer
                PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                int PasswordSize = password.Length * sizeof(byte);

                // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                unsafe
                {
                    byte[] PlainTextBytes = new byte[PlainTextSize];
                    fixed (byte* ptr1 = PlainTextBytes)
                    {
                        byte[] PasswordBytes = new byte[PasswordSize];
                        fixed (byte* ptr2 = PasswordBytes)
                        {
                            try
                            {
                                Marshal.Copy(PlainTextPtr, PlainTextBytes, 0, PlainTextSize);
                                Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                                PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(PasswordBytes, Encoding.ASCII.GetBytes("RMSecureString"), "SHA512", 12345);
                                using (RijndaelManaged SymmetricKey = new RijndaelManaged())
                                {
                                    SymmetricKey.Mode = CipherMode.CBC;
                                    using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(DerivedPassword.GetBytes(32), DerivedPassword.GetBytes(16)))
                                    {
                                        using (MemoryStream MemStream = new MemoryStream())
                                        {
                                            using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                                            {
                                                CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                                                CryptoStream.FlushFinalBlock();

                                                Result = "e" + Convert.ToBase64String(MemStream.ToArray());
                                            }
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                // Ensure managed array is cleared
                                Array.Clear(PlainTextBytes, 0, PlainTextSize);

                                // Ensure managed array is cleared
                                Array.Clear(PasswordBytes, 0, PasswordSize);
                            }
                        }
                    }
                }
            }
            finally
            {
                // Ensure unmanaged memory is released.
                if (PlainTextPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PlainTextPtr);
                }

                // Ensure unmanaged memory is released.
                if (PasswordPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                }
            }

            return Result;
        }
示例#23
0
        public void LoadFromEncryptedString(string encryptedString, RMSecureString password)
        {
            Clear();

            if (encryptedString.StartsWith("p"))
            {
                LoadFromProtectedString(encryptedString, password);
            }
            else if (encryptedString.StartsWith("e"))
            {
                // Trim leading 'e', which is just an indicator to say that this is an encrypted and not a protected string
                encryptedString = encryptedString.Substring(1);

                IntPtr PasswordPtr = IntPtr.Zero;

                try
                {
                    // Get the secure password string into a memory buffer
                    PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                    int PasswordSize = password.Length * sizeof(byte);

                    // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                    unsafe
                    {
                        byte[] Decrypted = null;
                        byte[] PasswordBytes = new byte[PasswordSize];
                        fixed (byte* ptr = PasswordBytes)
                        {
                            try
                            {
                                Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                                PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(PasswordBytes, Encoding.ASCII.GetBytes("RMSecureString"), "SHA512", 12345);
                                using (RijndaelManaged SymmetricKey = new RijndaelManaged())
                                {
                                    SymmetricKey.Mode = CipherMode.CBC;
                                    using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(DerivedPassword.GetBytes(32), DerivedPassword.GetBytes(16)))
                                    {
                                        using (MemoryStream MemStream = new MemoryStream(Convert.FromBase64String(encryptedString)))
                                        {
                                            using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                                            {
                                                byte[] DecryptedByte = new byte[1];

                                                int ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
                                                while (ByteCount > 0)
                                                {
                                                    if (_SecureStringSupported)
                                                    {
                                                        ((SecureString)_SecureString).AppendChar((char)DecryptedByte[0]);
                                                    }
                                                    else
                                                    {
                                                        ((StringBuilder)_SecureString).Append((char)DecryptedByte[0]);
                                                    }
                                                    ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                // Ensure managed array is cleared
                                if (Decrypted != null) Array.Clear(Decrypted, 0, Decrypted.Length);
                                Array.Clear(PasswordBytes, 0, PasswordSize);
                            }
                        }
                    }
                }
                finally
                {
                    // Ensure unmanaged memory is released.
                    if (PasswordPtr != IntPtr.Zero)
                    {
                        Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                    }
                }
            }
        }
示例#24
0
        public void LoadFromEncryptedString(string encryptedString, RMSecureString password)
        {
            Clear();

            if (encryptedString.StartsWith("p"))
            {
                LoadFromProtectedString(encryptedString, password);
            }
            else if (encryptedString.StartsWith("e"))
            {
                // Trim leading 'e', which is just an indicator to say that this is an encrypted and not a protected string
                encryptedString = encryptedString.Substring(1);

                IntPtr PasswordPtr = IntPtr.Zero;

                try
                {
                    // Get the secure password string into a memory buffer
                    PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
                    int PasswordSize = password.Length * sizeof(byte);

                    // Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
                    unsafe
                    {
                        byte[] Decrypted     = null;
                        byte[] PasswordBytes = new byte[PasswordSize];
                        fixed(byte *ptr = PasswordBytes)
                        {
                            try
                            {
                                Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);

                                PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(PasswordBytes, Encoding.ASCII.GetBytes("RMSecureString"), "SHA512", 12345);
                                using (RijndaelManaged SymmetricKey = new RijndaelManaged())
                                {
                                    SymmetricKey.Mode = CipherMode.CBC;
                                    using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(DerivedPassword.GetBytes(32), DerivedPassword.GetBytes(16)))
                                    {
                                        using (MemoryStream MemStream = new MemoryStream(Convert.FromBase64String(encryptedString)))
                                        {
                                            using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                                            {
                                                byte[] DecryptedByte = new byte[1];

                                                int ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
                                                while (ByteCount > 0)
                                                {
                                                    if (_SecureStringSupported)
                                                    {
                                                        ((SecureString)_SecureString).AppendChar((char)DecryptedByte[0]);
                                                    }
                                                    else
                                                    {
                                                        ((StringBuilder)_SecureString).Append((char)DecryptedByte[0]);
                                                    }
                                                    ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                // Ensure managed array is cleared
                                if (Decrypted != null)
                                {
                                    Array.Clear(Decrypted, 0, Decrypted.Length);
                                }
                                Array.Clear(PasswordBytes, 0, PasswordSize);
                            }
                        }
                    }
                }
                finally
                {
                    // Ensure unmanaged memory is released.
                    if (PasswordPtr != IntPtr.Zero)
                    {
                        Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
                    }
                }
            }
        }
示例#25
0
        /// <summary>
        /// Create an instance of the ConfigurationHelper with a specific location and filename for the INI
        /// </summary>
        /// <remarks>
        /// The INI will be stored in the given location with the given name.  If the Global or User Application Data folder is selected, the INI will be created in the Application.CompanyName subdirectory.
        /// </remarks>
        protected ConfigHelper(ConfigSaveLocation saveLocation, string fileName)
        {
            SectionName = "CONFIGURATION";

            IniPassword = new RMSecureString();
            Loaded = false;
            RMSecureStringPassword = new RMSecureString();

            switch (saveLocation)
            {
                case ConfigSaveLocation.Absolute:
                    FileName = fileName;
                    break;
                case ConfigSaveLocation.GlobalApplicationData:
                    FileName = StringUtils.PathCombine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), ProcessUtils.CompanyName, fileName);
                    break;
                case ConfigSaveLocation.Relative:
                    FileName = StringUtils.PathCombine(ProcessUtils.StartupPath, fileName);
                    break;
                case ConfigSaveLocation.UserApplicationData:
                    FileName = StringUtils.PathCombine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ProcessUtils.CompanyName, fileName);
                    break;
            }
        }
示例#26
0
        public static void Send(string smtp, int port, MailAddress from, MailAddress to, MailAddress sender, string subject, string body, string userName, RMSecureString password, bool ssl)
        {
            body = "<div style='background-color: #cccccc;'><h1>Error Message</h1>" + body + "</div>\r\n";

            body += AddCollection("QueryString", HttpContext.Current.Request.QueryString);
            body += AddCollection("Form", HttpContext.Current.Request.Form);
            body += AddCollection("Cookies", HttpContext.Current.Request.Cookies);
            body += AddCollection("Session", HttpContext.Current.Session);
            body += AddCollection("ServerVariables", HttpContext.Current.Request.ServerVariables);

            WebUtils.Email(smtp, port, from, to, sender, subject, body, true, userName, password, ssl);
        }
示例#27
0
文件: IniFile.cs 项目: Robin--/RMLib
        /// <summary>
        /// Custom constructor to load the given INI into memory, and indicate whether the changes should be buffered or immediately written to disk
        /// </summary>
        /// <param name="fileName">The INI to load</param>
        /// <param name="password">The password used to encrypt/decrypt the contents of the INI file</param>
        public IniFile(string fileName, RMSecureString password)
        {
            AutoSave = false;
            Password = new RMSecureString();

            _FileName = fileName;
            Password = password;

            List<string> CurrentComment = new List<string>();
            string CurrentSection = "";
            if (File.Exists(fileName))
            {
                // Read in the INI file
                string FileText = FileUtils.FileReadAllText(fileName, RMEncoding.Ansi);

                // Decrypt the INI file (if necessary)
                if (password.Length > 0)
                {
                    try
                    {
                        FileText = AES.Decrypt(FileText, password.GetPlainText(), INI_FILE_SALT);
                        Password = password;
                    }
                    catch (Exception)
                    {
                        return;
                    }
                }

                // Split the INI file into separate lines
                string[] Lines = FileText.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');

                // Loop through each line
                foreach (string Line in Lines)
                {
                    // Make sure the line isn't empty
                    if ((!string.IsNullOrEmpty(Line.Trim())))
                    {
                        // Check if this is a comment
                        if (Line.TrimStart().StartsWith(";"))
                        {
                            if (string.IsNullOrEmpty(CurrentSection))
                            {
                                _HeaderComment.Add(Line.TrimStart().Substring(1));
                            }
                            else
                            {
                                CurrentComment.Add(Line.TrimStart().Substring(1));
                            }
                        }
                        else
                        {
                            // Check if this is a new section
                            if ((Line.TrimStart().StartsWith("[")) && (Line.TrimEnd().EndsWith("]")))
                            {
                                // It is, so add the new section
                                CurrentSection = Line.Trim().Substring(1, Line.Trim().Length - 2);
                                _Sections[CurrentSection] = new IniFileSection(CurrentComment);
                                _SectionNames.Add(CurrentSection);
                                CurrentComment = new List<string>();
                            }
                            else
                            {
                                // It isn't so add the key/value to the current section
                                if (!string.IsNullOrEmpty(CurrentSection))
                                {
                                    // Make sure this line is in the KEY=VALUE form
                                    int EqualPos = Line.IndexOf('=');
                                    if (EqualPos >= 1)
                                    {
                                        // Get the key
                                        string Key = Line.Substring(0, EqualPos);

                                        // Get the value
                                        string Value = Line.Substring(EqualPos + 1);

                                        // Add the key/value pair to the dictionary
                                        _Sections[CurrentSection].WriteString(CurrentComment, Key, Value);
                                        CurrentComment = new List<string>();
                                    }
                                }
                            }
                        }
                    }
                }

                // Ensure the supplied password is valid
                if (Password.Length > 0)
                {
                    if ((_HeaderComment.Count == 0) || (_HeaderComment[0] != INI_FILE_ENCRYPTED_HEADER))
                    {
                        // Password did not properly decrypt the ini file
                        _Sections.Clear();
                        _SectionNames.Clear();
                        return;
                    }
                }
            }
        }