/// <summary>
        /// 从加密文件中读取连接字符串
        /// </summary>
        public static void LoadConnectionStrings()
        {
            // <connectionStrings configSource="connections.config"></connectionStrings>

            AMS.Profile.IProfile profile = new AMS.Profile.Xml(IOHelper.GetDataDirectory() + "\\Dbs.dat");
            string skey = profile.GetValue("ConnectionStringSetting", "Key", string.Empty);

            if (!string.IsNullOrEmpty(skey))
            {
                string cryptedConnectionStrings = profile.GetValue("ConnectionStringSetting", "ConnectionString", string.Empty);
                if (!string.IsNullOrEmpty(cryptedConnectionStrings))
                {
                    string connectionStrings = Cryptographer.DecryptSymmetric(cryptedConnectionStrings, skey);
                    if (!string.IsNullOrEmpty(connectionStrings))
                    {
                        string tempConfigFileName = IOHelper.GetDataDirectory() + "\\temp.config";
                        System.IO.File.WriteAllText(tempConfigFileName, connectionStrings, Encoding.UTF8);

                        ExeConfigurationFileMap configMap = new ExeConfigurationFileMap {
                            ExeConfigFilename = tempConfigFileName
                        };
                        Configuration externalConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

                        foreach (ConnectionStringSettings i in externalConfig.ConnectionStrings.ConnectionStrings)
                        {
                            SystemHelper.ChangeConnectionString(i.Name, i.ConnectionString, i.ProviderName);
                        }
                        System.IO.File.Delete(tempConfigFileName);
                    }
                }
            }
        }
        /// <summary>
        /// Decrypts a set of bytes and displayed the decrypted contents.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event arguments.</param>
        private void decryptButton_Click(object sender, System.EventArgs e)
        {
            if (this.encryptedContentsBase64 != null)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;

                    // Descrypt and display value
                    string readableString = Cryptographer.DecryptSymmetric(symmProvider, this.encryptedContentsBase64);
                    this.DisplayResults(string.Format(Resources.Culture, Resources.DecryptedTextMessage, readableString));
                }
                catch (Exception ex)
                {
                    ProcessUnhandledException(ex);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
            else
            {
                this.DisplayResults(Resources.DecryptErrorMessage);
            }
        }
Exemplo n.º 3
0
 ///--------------------------------------------------------------------------------
 /// <summary>This method gets an application setting as a string.</summary>
 ///
 /// <param name="valueToDecrypt">The value to decrypt.</param>
 ///
 /// <remarks>A  symmetric provider called "RijndaelManaged" must be defined through
 /// the Microsoft Enterprise Library 4.1 Configuration.</remarks>
 ///
 /// <returns>A decrypted string.</returns>
 ///--------------------------------------------------------------------------------
 public static string DecryptSymmetric(string valueToDecrypt)
 {
     if (String.IsNullOrEmpty(valueToDecrypt))
     {
         return(null);
     }
     return(Cryptographer.DecryptSymmetric("RijndaelManaged", valueToDecrypt));
 }
Exemplo n.º 4
0
        public void EncryptAndDecryptBytes()
        {
            byte[] encrypted = Cryptographer.EncryptSymmetric(symmInstance, plainTextBytes);
            Assert.IsFalse(CryptographyUtility.CompareBytes(plainTextBytes, encrypted));

            byte[] decrypted = Cryptographer.DecryptSymmetric(symmInstance, encrypted);
            Assert.IsTrue(CryptographyUtility.CompareBytes(plainTextBytes, decrypted));
        }
Exemplo n.º 5
0
        public void EncryptAndDecryptString()
        {
            string encrypted = Cryptographer.EncryptSymmetric(symmInstance, plainTextString);

            Assert.IsFalse(plainTextString == encrypted);

            string decrypted = Cryptographer.DecryptSymmetric(symmInstance, encrypted);

            Assert.IsTrue(plainTextString == decrypted);
        }
Exemplo n.º 6
0
        public void EncryptAndDecryptStringWithASymmetricAlgorithm()
        {
            string encrypted = Cryptographer.EncryptSymmetric(symmetricAlgorithm1, plainTextString);

            Assert.IsFalse(plainTextString == encrypted);

            string decrypted = Cryptographer.DecryptSymmetric(symmetricAlgorithm1, encrypted);

            Assert.IsTrue(plainTextString == decrypted);
        }
 internal string UnEncodePassword(string pass)
 {
     byte[] bIn  = Convert.FromBase64String(pass);
     byte[] bRet = Cryptographer.DecryptSymmetric("Custom Symmetric Cryptography Provider", bIn);
     if (bRet == null)
     {
         return(null);
     }
     return(Encoding.UTF8.GetString(bRet));
     //return Cryptographer.DecryptSymmetric("RijndaelManaged",pass);
 }
        static void Main(string[] args)
        {
            string Encrypt = Cryptographer.EncryptSymmetric("RC2CryptoServiceProvider", "Hello,World! ---你好,世界!");

            Console.WriteLine("密文:" + Encrypt);

            Console.WriteLine("---------------------------------------------------");

            Encrypt = Cryptographer.DecryptSymmetric("RC2CryptoServiceProvider", Encrypt);

            Console.WriteLine("原文:" + Encrypt);
        }
Exemplo n.º 9
0
        public void EncryptAndDecryptOneByte()
        {
            byte[] onebyte = new byte[1];
            CryptographyUtility.GetRandomBytes(onebyte);

            byte[] encrypted = Cryptographer.EncryptSymmetric(symmInstance, onebyte, context);
            Assert.IsFalse(CryptographyUtility.CompareBytes(onebyte, encrypted), "enc");

            byte[] decrypted = Cryptographer.DecryptSymmetric(symmInstance, encrypted, context);

            Assert.IsTrue(CryptographyUtility.CompareBytes(onebyte, decrypted), "dec");
        }
Exemplo n.º 10
0
        public void EncryptAndDecryptOneMegabyte()
        {
            byte[] megabyte = new byte[1024 * 1024];
            CryptographyUtility.GetRandomBytes(megabyte);

            byte[] encrypted = Cryptographer.EncryptSymmetric(symmInstance, megabyte);
            Assert.IsFalse(CryptographyUtility.CompareBytes(megabyte, encrypted));

            byte[] decrypted = Cryptographer.DecryptSymmetric(symmInstance, encrypted);

            Assert.IsTrue(CryptographyUtility.CompareBytes(megabyte, decrypted));
        }
Exemplo n.º 11
0
 static public string InternalDecryptValue(string symmProvider, string value)
 {
     try
     {
         var result = !string.IsNullOrEmpty(value) ? Cryptographer.DecryptSymmetric(symmProvider, value) : value;
         return(result);
     }
     catch (Exception ex)
     {
         DebugLog(ex.Message + " " + value, "InternalDecryptValue");
         return(value);
     }
 }
Exemplo n.º 12
0
        // App.config中添加symmetricCryptoProviders节点(对称秘钥加密)
        static void test2()
        {
            string Encrypt = Cryptographer.EncryptSymmetric("DPAPI Symmetric Crypto Provider", "SensitiveData");

            Console.WriteLine("密文:" + Encrypt);

            Console.WriteLine("--------------------------------------------");

            // 测试数据篡改后效果
            //Encrypt = Encrypt.Replace("A", "B");

            Encrypt = Cryptographer.DecryptSymmetric("DPAPI Symmetric Crypto Provider", Encrypt);

            Console.WriteLine("原文:" + Encrypt);
        }
 public static string DecryptEnterprise(string str)
 {
     if (string.IsNullOrEmpty(str))
     {
         return(str);
     }
     try
     {
         return(Cryptographer.DecryptSymmetric("OLBSymmProvider", str));
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return(str);
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Encrypts the XML fields.
        /// </summary>
        /// <param name="doc">The doc.</param>
        /// <param name="ahsId">The ahs id.</param>
        /// <param name="lobCd">The lob cd.</param>
        /// <param name="type">The type.</param>
        /// <param name="decrypt">if set to <c>true</c> [decrypt].</param>
        /// <returns></returns>
        static public string EncryptXmlFields(string doc, string ahsId, string lobCd, string type, bool decrypt)
        {
            var results = doc;

            try
            {
                var encryptDoc = new XmlDocument();
                encryptDoc.LoadXml(doc);
                var root = encryptDoc.DocumentElement;
                if (null != root)
                {
                    var encyptAttributes = new EncryptAttributeSet {
                        AhsId = ahsId, LobCd = lobCd, EncryptType = type
                    };
                    Assert.Test(encyptAttributes.Execute(), encyptAttributes.LastError);

                    foreach (DataRow encryptRow in encyptAttributes)
                    {
                        var attributeName = encryptRow[(int)EncryptAttributeSet.ResultList.AttributeName].ToString();
                        var nodes         = encryptDoc.SelectNodes(attributeName);

                        if (null == nodes)
                        {
                            continue;
                        }
                        foreach (XmlNode node in nodes)
                        {
                            if (string.IsNullOrEmpty(node.InnerText))
                            {
                                continue;
                            }
                            node.InnerText = decrypt ? Cryptographer.DecryptSymmetric(SymmProvider, node.InnerText) : Cryptographer.EncryptSymmetric(SymmProvider, node.InnerText);
                        }
                    }
                    results = encryptDoc.OuterXml;
                }
            }
            catch (Exception ex)
            {
                ErrorLog.LogError("EncryptXmlFields(): " + ex.Message, ServiceName);
            }
            return(results);
        }
Exemplo n.º 15
0
        public static void Main()
        {
            Console.WriteLine("Enter string to encrypt:");
            string stringToEncrypt = Console.ReadLine();

            // encrypt
            byte[] valueToEncrypt    = Encoding.Unicode.GetBytes(stringToEncrypt);
            byte[] encryptedContents = Cryptographer.EncryptSymmetric("My DPAPI Symmetric Cryptography Provider", valueToEncrypt);

            string stringToDecrypt = (new UnicodeEncoding()).GetString(encryptedContents);

            Console.WriteLine("Encrypted as \"{0}\"", stringToDecrypt);

            // decrypt
            byte[] valueToDecrypt    = Encoding.Unicode.GetBytes(stringToDecrypt);
            byte[] decryptedContents = Cryptographer.DecryptSymmetric("My DPAPI Symmetric Cryptography Provider", valueToDecrypt);
            string plainText         = (new UnicodeEncoding()).GetString(decryptedContents);

            Console.WriteLine("Decrypted to \"{0}\"", plainText);

            // hashing
            string stringValueToHash = "password";

            byte[] valueToHash   = (new UnicodeEncoding()).GetBytes(stringValueToHash);
            byte[] generatedHash = Cryptographer.CreateHash("MySHA1Managed", valueToHash);
            string hashString    = (new UnicodeEncoding()).GetString(generatedHash);

            Console.WriteLine("Hash of \"{0}\" is \"{1}\"", stringValueToHash, hashString);

            byte[] stringToCompare     = (new UnicodeEncoding()).GetBytes(stringValueToHash);
            bool   comparisonSucceeded = Cryptographer.CompareHash("MySHA1Managed", stringToCompare, generatedHash);

            Console.WriteLine("\"{0}\" hashes to \"{1}\" = {2} ", stringValueToHash, hashString, comparisonSucceeded);

            Console.Read();
        }
 public void DecryptWithZeroLengthInstanceThrows()
 {
     Cryptographer.DecryptSymmetric(string.Empty, plainTextBytes);
 }
Exemplo n.º 17
0
 /// <summary>
 /// 3DES解密
 /// </summary>
 /// <param name="decryptString"></param>
 /// <returns></returns>
 public static string TripleDESDecrypt(string decryptString)
 {
     return(Cryptographer.DecryptSymmetric("TripleDESCryptoServiceProvider", decryptString));
 }
Exemplo n.º 18
0
 /// <summary>
 /// Descriptografa um valor no algoritmo Simétrico de Rijndael do Enterprise Library 4. Com método definido no webconfig
 /// </summary>
 /// <param name="value">Valor criptografado a ser descriptografado</param>
 /// <returns>Retorna o valor em texto pleno do valor passado por parâmentro</returns>
 public static string DecryptSymmetric(string value)
 {
     return(Cryptographer.DecryptSymmetric("SpongeBuilderKey", value));
 }
 public void DecryptWithNullInstanceStringThrows()
 {
     Cryptographer.DecryptSymmetric(null, plainTextString);
 }
 public void DecryptWithInvalidStringThrows()
 {
     Cryptographer.DecryptSymmetric(symmInstance, "INVALID");
 }
Exemplo n.º 21
0
 public static string Decrypt(string encryptedtext)
 {
     return(Cryptographer.DecryptSymmetric("ForTestingProvider", encryptedtext));
 }
Exemplo n.º 22
0
 public void DecryptWithZeroLengthInstanceString()
 {
     Cryptographer.DecryptSymmetric(string.Empty, plainTextString, context);
 }
Exemplo n.º 23
0
 public void DecryptWithInvalidString()
 {
     Cryptographer.DecryptSymmetric(symmInstance, "INVALID", context);
 }
Exemplo n.º 24
0
 public void DecryptWithNullInstance()
 {
     Cryptographer.DecryptSymmetric(null, plainTextBytes, context);
 }
Exemplo n.º 25
0
 public void DecryptWithNullInstanceString()
 {
     Cryptographer.DecryptSymmetric(null, plainTextString, context);
 }
 public void DecryptSymmetricWithEmptyStringCipherTextThrows()
 {
     Cryptographer.DecryptSymmetric(symmInstance, (string)null);
 }
 public void DecryptWithNullInstanceThrows()
 {
     Cryptographer.DecryptSymmetric(null, plainTextBytes);
 }
Exemplo n.º 28
0
        private bool ValidateUser()
        {
            bool IsAuthenticated = false;

            DataCommandService dataCommandDB = DataCommandService.GetInstance();
            PageDB             pageDB        = new PageDB();
            DataTable          data          = null;
            string             password      = String.Empty;

            List <ScreenDataCommandParameter> parameters = pageDB.GetPopulatedCommandParameters(Me.ProfileCommand, Page);

            foreach (ScreenDataCommandParameter p in parameters)
            {
                if (p.Name.ToLower() == Me.UserNameParameter.ToLower())
                {
                    LoginName = Page.GetEntityIDValue(Page.Screen, p.InputKey, p.InputType);
                    break;
                }
            }
            password = Page.GetEntityIDValue(Page.Screen, Me.PasswordEntityID, Me.PasswordEntityInputType);

            data = dataCommandDB.GetDataForDataCommand(Me.ProfileCommand, parameters);

            if (data.Rows.Count == 1)
            {
                profile = data.Rows[0];
                string dbPassword = profile[Me.PasswordField].ToString();

                PasswordMode mode = Me.PasswordMode;

                if (!String.IsNullOrEmpty(dbPassword))
                {
                    switch (mode)
                    {
                    case PasswordMode.Hash:
                        if (Cryptographer.CompareHash(Me.PasswordAlgorithm, password, dbPassword))
                        {
                            IsAuthenticated = true;
                        }



                        break;

                    case PasswordMode.Encrypted:
                        string decryptedPassword = Cryptographer.DecryptSymmetric(Me.PasswordAlgorithm, dbPassword);
                        if (decryptedPassword == password)
                        {
                            IsAuthenticated = true;
                        }
                        break;

                    case PasswordMode.PlainText:
                        if (dbPassword == password)
                        {
                            IsAuthenticated = true;
                        }
                        break;
                    }
                }
            }

            return(IsAuthenticated);
        }
 protected override byte[] DecryptPassword(byte[] encodedPassword)
 {
     return(Cryptographer.DecryptSymmetric("Custom Symmetric Cryptography Provider", encodedPassword));
 }
Exemplo n.º 30
0
        /// <summary>
        /// 从加密文件中读取连接字符串
        /// </summary>
        public static bool LoadConnectionStrings()
        {
            try
            {
                if (ConfigurationManager.ConnectionStrings[DataConnectionStringName] != null)
                {
                    return(false);
                }

                // <connectionStrings configSource="connections.config"></connectionStrings>

                AMS.Profile.IProfile profile = new AMS.Profile.Xml(SystemDirectory.DataDirectory + "\\Dbs.dat");
                string skey = profile.GetValue("ConnectionStringSetting", "Key", string.Empty);

                if (!string.IsNullOrEmpty(skey))
                {
                    string cryptedConnectionStrings = profile.GetValue("ConnectionStringSetting", "ConnectionString", string.Empty);
                    if (!string.IsNullOrEmpty(cryptedConnectionStrings))
                    {
                        string connectionStrings = Cryptographer.DecryptSymmetric(cryptedConnectionStrings, skey);
                        if (!string.IsNullOrEmpty(connectionStrings))
                        {
                            string tempConfigFileName = SystemDirectory.DataDirectory + "\\temp.config";
                            System.IO.File.WriteAllText(tempConfigFileName, connectionStrings, Encoding.UTF8);

                            ExeConfigurationFileMap configMap = new ExeConfigurationFileMap {
                                ExeConfigFilename = tempConfigFileName
                            };
                            Configuration externalConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

                            Configuration exeConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                            foreach (ConnectionStringSettings i in externalConfig.ConnectionStrings.ConnectionStrings)
                            {
                                if (exeConfig.ConnectionStrings.ConnectionStrings[i.Name] == null)
                                {
                                    exeConfig.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(i.Name, i.ConnectionString, i.ProviderName));
                                }
                                else
                                {
                                    //the full name of the connection string can be found in the app.config file
                                    // in the "name" attribute of the connection string
                                    exeConfig.ConnectionStrings.ConnectionStrings[i.Name].ConnectionString = i.ConnectionString;
                                    exeConfig.ConnectionStrings.ConnectionStrings[i.Name].ProviderName     = i.ProviderName;
                                }
                            }
                            if (!exeConfig.ConnectionStrings.SectionInformation.IsProtected)
                            {
                                //exeConfig.ConnectionStrings.SectionInformation.UnprotectSection();
                                // Encrypt the section.
                                exeConfig.ConnectionStrings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                            }

                            exeConfig.Save(ConfigurationSaveMode.Full);
                            ConfigurationManager.RefreshSection(exeConfig.ConnectionStrings.SectionInformation.Name);

                            // re-init ConfigurationManager
                            var constructorInfo = typeof(System.Configuration.ConfigurationManager).GetConstructor(
                                System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic, null, new Type[0], null);
                            constructorInfo.Invoke(null, null);

                            System.IO.File.Delete(tempConfigFileName);
                        }
                    }
                }
                return(true);
            }
            catch (System.Configuration.ConfigurationErrorsException)
            {
                RemoveEncryptedData();
                throw;
            }
        }