Exemplo n.º 1
0
        private static string Encrypt(string hashKey, string strQueryStringParameter)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider hash_func = new System.Security.Cryptography.MD5CryptoServiceProvider();

            byte[] key = hash_func.ComputeHash(Encoding.ASCII.GetBytes(hashKey));
            byte[] IV  = new byte[hashKey.Length];

            System.Security.Cryptography.SHA1CryptoServiceProvider sha_func = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            byte[] temp = sha_func.ComputeHash(Encoding.ASCII.GetBytes(hashKey));

            for (int i = 0; i < hashKey.Length; i++)
            {
                IV[i] = temp[hashKey.Length];
            }

            byte[] toenc = System.Text.Encoding.UTF8.GetBytes(strQueryStringParameter);

            System.Security.Cryptography.TripleDESCryptoServiceProvider des =
                new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            des.KeySize = 128;
            MemoryStream ms = new MemoryStream();

            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(
                ms,
                des.CreateEncryptor(key, IV),
                System.Security.Cryptography.CryptoStreamMode.Write
                );
            cs.Write(toenc, 0, toenc.Length);
            cs.FlushFinalBlock();

            return(Convert.ToBase64String(ms.ToArray()));
        }
Exemplo n.º 2
0
        // http://www.codeproject.com/KB/aspnet/ASPNET_20_Webconfig.aspx
        // http://www.codeproject.com/KB/database/Connection_Strings.aspx
        public static string DeCrypt(string SourceText)
        {
            string strReturnValue = "";

            if (string.IsNullOrEmpty(SourceText))
            {
                return(strReturnValue);
            } // End if (string.IsNullOrEmpty(SourceText))


            using (System.Security.Cryptography.TripleDESCryptoServiceProvider Des = new System.Security.Cryptography.TripleDESCryptoServiceProvider())
            {
                using (System.Security.Cryptography.MD5CryptoServiceProvider HashMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
                {
                    string strSymmetricKey = GetSymmetricKey();
                    Des.Key  = HashMD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSymmetricKey));
                    Des.Mode = System.Security.Cryptography.CipherMode.ECB;

                    System.Security.Cryptography.ICryptoTransform desdencrypt = Des.CreateDecryptor();
                    byte[] buff = System.Convert.FromBase64String(SourceText);
                    strReturnValue = System.Text.Encoding.UTF8.GetString(desdencrypt.TransformFinalBlock(buff, 0, buff.Length));
                } // End Using HashMD5
            }     // End Using Des

            return(strReturnValue);
        } // End Function DeCrypt
Exemplo n.º 3
0
        public static string Decrypt3DES(string msg, string key, string iv)
        {
            string result = string.Empty;

            byte [] arrMsg = Convert.FromBase64String(msg);

            var provider = new System.Security.Cryptography.TripleDESCryptoServiceProvider()
            {
                Key     = System.Text.Encoding.UTF8.GetBytes(GF.getMD5(key)),               //Convert.FromBase64String(GF.getMD5(key)),
                IV      = System.Text.Encoding.UTF8.GetBytes(iv),
                Mode    = System.Security.Cryptography.CipherMode.CBC,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform ct = provider.CreateDecryptor();

            try {
                var arrResult = ct.TransformFinalBlock(arrMsg, 0, arrMsg.Length);
                result = System.Text.Encoding.UTF8.GetString(arrResult);
            } catch {
                //Console.Write ("X");
            }

            return(result);
        }
Exemplo n.º 4
0
        public static string DS(string toEncrypt)
        {
            string key = "k29vn - Đặng Đức Kiên";

            if (string.IsNullOrEmpty(MrkKEY))
            {
                key = "k29vn - Đặng Đức Kiên";
            }
            else
            {
                key = MrkKEY;
            }
            string rt = string.Empty;

            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
                System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
                tdes.Key     = keyArray;
                tdes.Mode    = System.Security.Cryptography.CipherMode.ECB;
                tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                System.Security.Cryptography.ICryptoTransform cTransform = tdes.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                rt = System.Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch { rt = string.Empty; }
            return(rt);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Decrypt the specified string using the <see cref="System.Security.Cryptography.TripleDESCryptoServiceProvider" /> cryptographic
        /// service provider. It is expected that <see cref="Business.Interfaces.IAppSetting.EncryptionKey" /> is used for the encryption key.
        /// </summary>
        /// <param name="encryptedText">A string to be decrypted. The encrypted string should have been encrypted using the
        /// <see cref="Encrypt" /> function in this class. If the value is null or empty, the return value is equal to String.Empty.</param>
        /// <param name="encryptionKey">The encryption key.</param>
        /// <returns>Returns the original, unencrypted string contained in the <paramref name="encryptedText" /> parameter.</returns>
        /// <exception cref="System.FormatException">Thrown when the text cannot be decrypted.</exception>
        public static string Decrypt(string encryptedText, string encryptionKey)
        {
            if (String.IsNullOrEmpty(encryptedText))
            {
                return(String.Empty);
            }

            // Get the byte code of the string
            byte[] toEncryptArray = Convert.FromBase64String(encryptedText);

            using (var tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider())
            {
                // Set the secret key for the tripleDES algorithm.
                tdes.Key = System.Text.Encoding.UTF8.GetBytes(encryptionKey);

                // Mode of operation. there are other 4 modes. We choose ECB(Electronic code Book)
                tdes.Mode = System.Security.Cryptography.CipherMode.ECB;

                // Padding mode(if any extra byte added)
                tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

                var    cTransform  = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                // Release resources held by TripleDes Encryptor
                tdes.Clear();

                // Return the Clear decrypted TEXT
                return(System.Text.Encoding.UTF8.GetString(resultArray));
            }
        }
Exemplo n.º 6
0
        public static byte[] GetEmbeddedBytes(String file)
        {
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(file))
            {
                if (stream != null)
                {
                    var assemblyData = new Byte[stream.Length];
                    stream.Read(assemblyData, 0, assemblyData.Length);

                    var    key       = System.Text.Encoding.ASCII.GetBytes("t7n6cVWf9Tbns0eI");
                    var    iv        = System.Text.Encoding.ASCII.GetBytes("9qh17ZUf");
                    var    provider  = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
                    var    transform = provider.CreateDecryptor(key, iv);
                    byte[] bytes;
                    using (var cstream = new MemoryStream())
                    {
                        using (var cryptoStream = new System.Security.Cryptography.CryptoStream(cstream, transform, System.Security.Cryptography.CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(assemblyData, 0, assemblyData.Length);
                            cryptoStream.FlushFinalBlock();
                            bytes = cstream.ToArray();

                            using (var compressedStream = new MemoryStream(bytes))
                                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                                    using (var resultStream = new MemoryStream())
                                    {
                                        zipStream.CopyTo(resultStream);
                                        return(resultStream.ToArray());
                                    }
                        }
                    }
                }
            }
            return(null);
        }
Exemplo n.º 7
0
        /// <summary>
        /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
        /// </summary>
        /// <param name="cipherString">encrypted string</param>
        /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>
        /// <returns></returns>
        public static string Decrypt(string cipherString, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Convert.FromBase64String(cipherString);

            //System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
            //Get your key from config file to open the lock!
            //string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

            if (useHashing)
            {
                System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }

            System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            tdes.Key     = keyArray;
            tdes.Mode    = System.Security.Cryptography.CipherMode.ECB;
            tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            System.Security.Cryptography.ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            tdes.Clear();
            return(UTF8Encoding.UTF8.GetString(resultArray));
        }
Exemplo n.º 8
0
        public static string Descriptografar(string Message)
        {
            byte[] Results;

            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            System.Security.Cryptography.MD5CryptoServiceProvider HashProvider = new System.Security.Cryptography.MD5CryptoServiceProvider();

            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(senha));

            System.Security.Cryptography.TripleDESCryptoServiceProvider TDESAlgorithm = new System.Security.Cryptography.TripleDESCryptoServiceProvider();

            TDESAlgorithm.Key = TDESKey;

            TDESAlgorithm.Mode = System.Security.Cryptography.CipherMode.ECB;

            TDESAlgorithm.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            byte[] DataToDecrypt = Convert.FromBase64String(Message);

            try
            {
                System.Security.Cryptography.ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();

                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }
            return(UTF8.GetString(Results));
        }
Exemplo n.º 9
0
        ///// <summary>
        ///// Gets the connection string settings for the connection string associated with the gallery data.
        ///// </summary>
        ///// <returns>An instance of <see cref="System.Configuration.ConnectionStringSettings" />.</returns>
        //public static System.Configuration.ConnectionStringSettings GetConnectionStringSettings()
        //{
        //  return System.Configuration.ConfigurationManager.ConnectionStrings.Cast<System.Configuration.ConnectionStringSettings>().First(cnStringObj => cnStringObj.Name == GetConnectionStringName());
        //}

        ///// <summary>
        ///// Gets the name of the connection string for the gallery data.
        ///// </summary>
        ///// <returns>System.String.</returns>
        //private static string GetConnectionStringName()
        //{
        //  using (var repo = new GalleryRepository())
        //  {
        //    return repo.ConnectionStringName;
        //  }
        //}


        /// <summary>
        /// Encrypt the specified string using the <see cref="System.Security.Cryptography.TripleDESCryptoServiceProvider" /> cryptographic
        /// service provider. It is expected that <see cref="Business.Interfaces.IAppSetting.EncryptionKey" /> is used for the encryption key.
        /// The encrypted string can be decrypted to its original string using the <see cref="Decrypt" /> function in this class.
        /// </summary>
        /// <param name="plainText">A plain text string to be encrypted. If the value is null or empty, the return value is
        /// equal to String.Empty.</param>
        /// <param name="encryptionKey">The encryption key.</param>
        /// <returns>Returns an encrypted version of the <paramref name="plainText" /> parameter.</returns>
        public static string Encrypt(string plainText, string encryptionKey)
        {
            if (String.IsNullOrEmpty(plainText))
            {
                return(String.Empty);
            }

            // This method (and the Decrypt method) inspired from Code Project.
            // http://www.codeproject.com/useritems/Cryptography.asp
            byte[] stringToEncryptArray = System.Text.Encoding.UTF8.GetBytes(plainText);

            using (var tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider())
            {
                // Set the secret key for the tripleDES algorithm
                tdes.Key = System.Text.Encoding.UTF8.GetBytes(encryptionKey);

                // Mode of operation. there are other 4 modes. We choose ECB (Electronic code Book)
                tdes.Mode = System.Security.Cryptography.CipherMode.ECB;

                //padding mode(if any extra byte added)
                tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

                // Transform the specified region of bytes array to resultArray
                var    cTransform  = tdes.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(stringToEncryptArray, 0, stringToEncryptArray.Length);

                // Release resources held by TripleDes Encryptor
                tdes.Clear();

                // Return the encrypted data into unreadable string format
                return(Convert.ToBase64String(resultArray));
            }
        }
Exemplo n.º 10
0
        public void GenerateBase64Key()
        {
            System.Security.Cryptography.TripleDESCryptoServiceProvider desc = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            desc.GenerateKey();
            string key = Convert.ToBase64String(desc.Key);

            Console.WriteLine(key);
        }
Exemplo n.º 11
0
        private static string Encrypt(string text, System.Security.Cryptography.TripleDESCryptoServiceProvider Des)
        {
            System.Security.Cryptography.ICryptoTransform desdencrypt = Des.CreateEncryptor();
            dynamic MyASCIIEncoding = new System.Text.ASCIIEncoding();

            byte[] buff = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
            return(Convert.ToBase64String(desdencrypt.TransformFinalBlock(buff, 0, buff.Length)));
        }
Exemplo n.º 12
0
 /// <summary>
 /// Creates the CryptoServiceProvider based on the PBKDF2.
 /// </summary>
 /// <param name="inPBKDF2">Input PBKDF2</param>
 /// <returns>CSP</returns>
 private System.Security.Cryptography.TripleDESCryptoServiceProvider createCSP(System.Security.Cryptography.Rfc2898DeriveBytes inPBKDF2)
 {
     inPBKDF2.Reset();
     csp         = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
     csp.Mode    = this.cipherMode;
     csp.Padding = this.paddingMode;
     csp.Key     = inPBKDF2.GetBytes(csp.KeySize / 8);
     csp.IV      = inPBKDF2.GetBytes(csp.BlockSize / 8);
     return(csp);
 }
Exemplo n.º 13
0
        private System.Security.Cryptography.TripleDES CreateDes(string key)
        {
            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            var des = new System.Security.Cryptography.TripleDESCryptoServiceProvider {
                Key = md5.ComputeHash(System.Text.Encoding.Unicode.GetBytes(key))
            };

            des.IV = new byte[des.BlockSize / 8];

            return(des);
        }
Exemplo n.º 14
0
        } // End Function Crypt

        public static string GenerateKey()
        {
            System.Security.Cryptography.TripleDESCryptoServiceProvider objDESprovider = new System.Security.Cryptography.TripleDESCryptoServiceProvider();

            objDESprovider.GenerateKey();
            objDESprovider.GenerateIV();
            byte[] bIV  = objDESprovider.IV;
            byte[] bKey = objDESprovider.Key;

            return("IV: " + AES.ByteArrayToHexString(bIV) + System.Environment.NewLine + "Key: " + AES.ByteArrayToHexString(bKey));
        } // End Function GenerateKey
        private static string EncryptDecryptText(bool isEncode, string text, string encryptionKey)
        {
            // Step 1. Hash the encryptionKey using MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below
            var hashProvider = new System.Security.Cryptography.MD5CryptoServiceProvider();
            var tdesKey      = hashProvider.ComputeHash(Encoding.Unicode.GetBytes(encryptionKey));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            var tdesAlgorithm = new System.Security.Cryptography.TripleDESCryptoServiceProvider
            {
                Key  = tdesKey,
                Mode =
                    System.Security
                    .Cryptography
                    .CipherMode.ECB,
                Padding =
                    System.Security
                    .Cryptography
                    .PaddingMode.PKCS7
            };

            // Step 3. Setup the encoder

            // Step 4. Convert the input text to a byte[]
            byte[] dataToEncryptDecrypt = isEncode ? Encoding.Unicode.GetBytes(text) : Convert.FromBase64String(text);

            // Step 5. Attempt to encrypt/Decrypt the string
            byte[] encryptDecryptedBytes;
            try
            {
                if (isEncode)
                {
                    var encryptor = tdesAlgorithm.CreateEncryptor();
                    encryptDecryptedBytes = encryptor.TransformFinalBlock(dataToEncryptDecrypt, 0,
                                                                          dataToEncryptDecrypt.Length);
                }
                else
                {
                    var decryptor = tdesAlgorithm.CreateDecryptor();
                    encryptDecryptedBytes = decryptor.TransformFinalBlock(dataToEncryptDecrypt, 0,
                                                                          dataToEncryptDecrypt.Length);
                }
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                tdesAlgorithm.Clear();
                hashProvider.Clear();
            }

            // Step 6. Return the encrypted string as a base64 encoded string
            return(isEncode ? Convert.ToBase64String(encryptDecryptedBytes) : Encoding.Unicode.GetString(encryptDecryptedBytes));
        }
Exemplo n.º 16
0
        //Decryption Method
        public string DecryptTripleDES(string base64Text, string Key)
        {
            System.Security.Cryptography.TripleDESCryptoServiceProvider DES     = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            System.Security.Cryptography.MD5CryptoServiceProvider       hashMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            DES.Key  = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(Key));
            DES.Mode = System.Security.Cryptography.CipherMode.ECB;
            System.Security.Cryptography.ICryptoTransform DESDecrypt = DES.CreateDecryptor();
            Buffer = Convert.FromBase64String(base64Text);
            string DecTripleDES = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));

            return(DecTripleDES);
        }
Exemplo n.º 17
0
 /// <summary>
 /// decrypt the string
 /// </summary>
 /// <param name="value"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public string Decrypt(string value, string key)
 {
     System.Security.Cryptography.TripleDESCryptoServiceProvider DES     = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
     System.Security.Cryptography.MD5CryptoServiceProvider       hashMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
     // scramble the key
     key = ScrambleKey(key);
     // Compute the MD5 hash.
     DES.Key = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key));
     // Set the cipher mode.
     DES.Mode = System.Security.Cryptography.CipherMode.ECB;
     // Create the decryptor.
     System.Security.Cryptography.ICryptoTransform DESDecrypt = DES.CreateDecryptor();
     byte[] Buffer = Convert.FromBase64String(value);
     // Transform and return the string.
     return(System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)));
 }
Exemplo n.º 18
0
        /// <summary>
        /// Encrypts a string using a specified security key with
        /// the option to hash.
        /// </summary>
        /// <param name="toEncrypt">String to encrypt</param>
        /// <param name="securityKey">The key to apply to the encryption</param>
        /// <param name="useHashing">Weather hashing is used</param>
        /// <returns>The encrpyted string</returns>
        private static string Encrypt(string toEncrypt, string securityKey, bool useHashing)
        {
            string retVal = string.Empty;

            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = System.Text.UTF8Encoding.UTF8.GetBytes(toEncrypt);
                // Validate inputs
                ValidateInput(toEncrypt);
                ValidateInput(securityKey);
                // If hashing use get hashcode regards to your key
                if (useHashing)
                {
                    System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                    keyArray = hashmd5.ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(securityKey));
                    // Always release the resources and flush data
                    // of the Cryptographic service provide. Best Practice
                    hashmd5.Clear();
                }
                else
                {
                    keyArray = System.Text.UTF8Encoding.UTF8.GetBytes(securityKey);
                }
                System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
                // Set the secret key for the tripleDES algorithm
                tdes.Key = keyArray;
                // Mode of operation. there are other 4 modes.
                // We choose ECB (Electronic code Book)
                tdes.Mode = System.Security.Cryptography.CipherMode.ECB;
                // Padding mode (if any extra byte added)
                tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                System.Security.Cryptography.ICryptoTransform cTransform = tdes.CreateEncryptor();
                // Transform the specified region of bytes array to resultArray
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                // Release resources held by TripleDes Encryptor
                tdes.Clear();
                // Return the encrypted data into unreadable string format
                retVal = Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(retVal);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Decrypts a specified key against the original security
        /// key, with the option to hash.
        /// </summary>
        /// <param name="cipherString">String to decrypt</param>
        /// <param name="securityKey">The original security key</param>
        /// <param name="useHashing">Weather hashing is enabled</param>
        /// <returns>The decrypted key</returns>
        private static string Decrypt(string cipherString, string securityKey, bool useHashing)
        {
            string retVal = string.Empty;

            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = Convert.FromBase64String(cipherString);
                // Validate inputs
                ValidateInput(cipherString);
                ValidateInput(securityKey);
                if (useHashing)
                {
                    // If hashing was used get the hash code with regards to your key
                    System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                    keyArray = hashmd5.ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(securityKey));
                    // Release any resource held by the MD5CryptoServiceProvider
                    hashmd5.Clear();
                }
                else
                {
                    // If hashing was not implemented get the byte code of the key
                    keyArray = System.Text.UTF8Encoding.UTF8.GetBytes(securityKey);
                }
                System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
                // Set the secret key for the tripleDES algorithm
                tdes.Key = keyArray;
                // Mode of operation. there are other 4 modes.
                // We choose ECB(Electronic code Book)
                tdes.Mode = System.Security.Cryptography.CipherMode.ECB;
                // Padding mode(if any extra byte added)
                tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                System.Security.Cryptography.ICryptoTransform cTransform = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                // Release resources held by TripleDes Encryptor
                tdes.Clear();
                // Return the Clear decrypted TEXT
                retVal = System.Text.UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(retVal);
        }
Exemplo n.º 20
0
        public static string Crypt(string SourceText)
        {
            using (System.Security.Cryptography.TripleDESCryptoServiceProvider TripleDes = new System.Security.Cryptography.TripleDESCryptoServiceProvider())
            {
                using (System.Security.Cryptography.MD5CryptoServiceProvider HashMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
                {
                    TripleDes.Key  = HashMD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(Key));
                    TripleDes.Mode = System.Security.Cryptography.CipherMode.ECB;
                    System.Security.Cryptography.ICryptoTransform desdencrypt = TripleDes.CreateEncryptor();
                    byte[] buff = System.Text.Encoding.UTF8.GetBytes(SourceText);

                    return(System.Convert.ToBase64String(desdencrypt.TransformFinalBlock(buff, 0, buff.Length)));
                }
            }

            return(string.Empty);
        }
Exemplo n.º 21
0
 private static string DeCrypt(string strDecypt, string key)
 {
     try
     {
         byte[] keyArr;
         byte[] DeCryptArr = Convert.FromBase64String(strDecypt);
         System.Security.Cryptography.MD5CryptoServiceProvider MD5Hash = new System.Security.Cryptography.MD5CryptoServiceProvider();
         keyArr = MD5Hash.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
         System.Security.Cryptography.TripleDESCryptoServiceProvider tripDes = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
         tripDes.Key     = keyArr;
         tripDes.Mode    = System.Security.Cryptography.CipherMode.ECB;
         tripDes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
         System.Security.Cryptography.ICryptoTransform transform = tripDes.CreateDecryptor();
         byte[] arrResult = transform.TransformFinalBlock(DeCryptArr, 0, DeCryptArr.Length);
         return(UTF8Encoding.UTF8.GetString(arrResult));
     }
     catch (Exception ex) { }
     return(string.Empty);
 }
Exemplo n.º 22
0
        public static string Operation(OperationType type, string Key, string text)
        {
            string _result = null;

            System.Security.Cryptography.MD5CryptoServiceProvider       hashMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            System.Security.Cryptography.TripleDESCryptoServiceProvider des     = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            des.Key  = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(Key));
            des.Mode = System.Security.Cryptography.CipherMode.ECB;
            if ((type == OperationType.Encrypt))
            {
                _result = Encrypt(text, des);
            }
            else
            {
                _result = Decrypt(text, des);
            }

            return(_result);
        }
Exemplo n.º 23
0
        public string Decrypt(string ciphertext)
        {
            System.Security.Cryptography.TripleDESCryptoServiceProvider cipher = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            cipher.BlockSize = 64;
            string plaintext;

            using (System.IO.MemoryStream plaintextStream = new System.IO.MemoryStream())
            {
                using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(plaintextStream, cipher.CreateDecryptor(this.Key, this.IV), System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    byte[] bytes = Convert.FromBase64String(ciphertext);
                    cryptoStream.Write(bytes, 0, bytes.Length);
                    cryptoStream.FlushFinalBlock();
                    plaintext = Encoding.UTF8.GetString(plaintextStream.ToArray());
                }
            }

            return(plaintext);
        }
Exemplo n.º 24
0
        public static string EncryptTripleDES(string Plaintext)
        {
            System.Security.Cryptography.TripleDESCryptoServiceProvider DES =

                new System.Security.Cryptography.TripleDESCryptoServiceProvider();

            System.Security.Cryptography.MD5CryptoServiceProvider hashMD5 =

                new System.Security.Cryptography.MD5CryptoServiceProvider();

            DES.Key = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(_key));

            DES.Mode = System.Security.Cryptography.CipherMode.ECB;

            System.Security.Cryptography.ICryptoTransform DESEncrypt = DES.CreateEncryptor();

            var    Buffer    = System.Text.ASCIIEncoding.ASCII.GetBytes(Plaintext);
            string TripleDES = Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));

            return(TripleDES);
        }
Exemplo n.º 25
0
        private static string Decrypt(string cipherString)
        {
            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = Convert.FromBase64String(cipherString);

                //Di default disabilito l'hashing
                bool useHashing = false;

                //La chiave deve essere di 24 caratteri
                string key = "ValueTeamDocsPa3Services";

                if (useHashing)
                {
                    System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                    keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                    hashmd5.Clear();
                }
                else
                {
                    keyArray = UTF8Encoding.UTF8.GetBytes(key);
                }

                System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
                tdes.Key     = keyArray;
                tdes.Mode    = System.Security.Cryptography.CipherMode.ECB;
                tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

                System.Security.Cryptography.ICryptoTransform cTransform = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                tdes.Clear();
                return(UTF8Encoding.UTF8.GetString(resultArray));
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 26
0
 public static string ES(string toDecrypt)
 {
     string key = "k29vn - Đặng Đức Kiên";
     if (string.IsNullOrEmpty(MrkKEY)) key = "k29vn - Đặng Đức Kiên";
     else key = MrkKEY;
     string rt = string.Empty;
     try
     {
         byte[] keyArray;
         byte[] toEncryptArray = System.Convert.FromBase64String(toDecrypt);
         System.Security.Cryptography.MD5CryptoServiceProvider hashmd5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
         keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
         System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
         tdes.Key = keyArray;
         tdes.Mode = System.Security.Cryptography.CipherMode.ECB;
         tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
         System.Security.Cryptography.ICryptoTransform cTransform = tdes.CreateDecryptor();
         byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
         rt = UTF8Encoding.UTF8.GetString(resultArray);
     }
     catch { rt = string.Empty; }
     return rt;
 }
Exemplo n.º 27
0
        public static string Decrypt(this String base64Text)
        {
            string TripleDESDecyrptedOutput = "";

            try
            {
                byte[] Buffer = new byte[] {
                    0
                };
                System.Security.Cryptography.TripleDESCryptoServiceProvider DES     = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
                System.Security.Cryptography.MD5CryptoServiceProvider       hashMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                DES.Key  = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes("252121112237244914192"));
                DES.Mode = System.Security.Cryptography.CipherMode.ECB;
                System.Security.Cryptography.ICryptoTransform DESDecrypt = DES.CreateDecryptor();
                Buffer = Convert.FromBase64String(base64Text);
                TripleDESDecyrptedOutput = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
                return(TripleDESDecyrptedOutput);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 28
0
        public static byte[] CompressEncrypt(byte[] raw)
        {
            byte[] zippedBytes;
            using (var memory = new MemoryStream())
            {
                using (var gzip = new GZipStream(memory, CompressionMode.Compress, true))
                    gzip.Write(raw, 0, raw.Length);
                zippedBytes = memory.ToArray();
            }
            var key       = System.Text.Encoding.ASCII.GetBytes("t7n6cVWf9Tbns0eI");
            var iv        = System.Text.Encoding.ASCII.GetBytes("9qh17ZUf");
            var provider  = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            var transform = provider.CreateEncryptor(key, iv);

            using (var stream = new MemoryStream())
            {
                using (var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, transform, System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    cryptoStream.Write(zippedBytes, 0, zippedBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    return(stream.ToArray());
                }
            }
        }
        static void Main(string[] args)
        {
            System.Security.Cryptography.TripleDESCryptoServiceProvider tripleDES = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            byte[] data = Encoding.UTF8.GetBytes("This is a sample message");
            byte[] key  = Encoding.UTF8.GetBytes("NOSTROMOHASSOMEGODPOWERS");
            tripleDES.Key = key;
            tripleDES.IV  = new byte[tripleDES.BlockSize / 8];
            var encryptor = tripleDES.CreateEncryptor();

            byte[] result = new byte[data.Length];
            result = encryptor.TransformFinalBlock(data, 0, data.Length);
            string res = BitConverter.ToString(result).Replace("-", "");

            Console.WriteLine(BitConverter.ToString(result).Replace("-", ""));

            byte[] data2 = result;
            tripleDES.Key = key;
            tripleDES.IV  = new byte[tripleDES.BlockSize / 8];
            var decryptor = tripleDES.CreateDecryptor();

            byte[] result2 = new byte[data2.Length];
            result2 = decryptor.TransformFinalBlock(data2, 0, data2.Length);
            Console.WriteLine(Encoding.UTF8.GetString(result2));
        }
Exemplo n.º 30
0
        public static string GenerateKey()
        {
            System.Security.Cryptography.TripleDESCryptoServiceProvider objDESprovider = new System.Security.Cryptography.TripleDESCryptoServiceProvider();

            objDESprovider.GenerateKey();
            objDESprovider.GenerateIV();
            byte[] bIV = objDESprovider.IV;
            byte[] bKey = objDESprovider.Key;

            return "IV: " + AES.ByteArrayToHexString(bIV) + System.Environment.NewLine + "Key: " + AES.ByteArrayToHexString(bKey);
        }
Exemplo n.º 31
0
        //Protected Shared strSymmetricKey As String = "Als symmetrischer Key kann irgendein Text verwendet werden. äöü'"
        // http://www.codeproject.com/KB/aspnet/ASPNET_20_Webconfig.aspx
        // http://www.codeproject.com/KB/database/Connection_Strings.aspx
        public static string DeCrypt(string SourceText)
        {
            string strReturnValue = "";

            if (string.IsNullOrEmpty(SourceText))
            {
                return strReturnValue;
            } // End if (string.IsNullOrEmpty(SourceText))

            using (System.Security.Cryptography.TripleDESCryptoServiceProvider Des = new System.Security.Cryptography.TripleDESCryptoServiceProvider())
            {

                using (System.Security.Cryptography.MD5CryptoServiceProvider HashMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
                {
                    Des.Key = HashMD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSymmetricKey));
                    Des.Mode = System.Security.Cryptography.CipherMode.ECB;

                    System.Security.Cryptography.ICryptoTransform desdencrypt = Des.CreateDecryptor();
                    byte[] buff = System.Convert.FromBase64String(SourceText);
                    strReturnValue = System.Text.Encoding.UTF8.GetString(desdencrypt.TransformFinalBlock(buff, 0, buff.Length));
                } // End Using HashMD5

            } // End Using Des

            return strReturnValue;
        }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            System.Security.Cryptography.TripleDESCryptoServiceProvider tripleDes = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            tripleDes.GenerateKey();
            Console.WriteLine("random tripleDes key:");
            StringBuilder sb1 = new StringBuilder(48);
            foreach (byte b in tripleDes.Key)
                sb1.Append(string.Format("{0:X2}", b));
            Console.WriteLine(sb1);

            int len = 128;
            byte[] buff = new byte[len / 2];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(buff);
            Console.WriteLine("random SHA1 key:");
            StringBuilder sb2 = new StringBuilder(len);
            for (int i = 0; i < buff.Length; i++)
                sb2.Append(string.Format("{0:X2}", buff[i]));
            Console.WriteLine(sb2);

            return;

            var data = new Dictionary<string, string>() { { "a", "33" }, { "b", ",444" } };
            int speed = 100;
            string res = null;

            Stopwatch sw = new Stopwatch();

            res = ClientAppAPIClient.GetInstance.Post("Default/Add", data);
            sw.Reset();
            sw.Restart();
            Console.WriteLine("start");
            for (var i = 0; i < speed; i++)
            {
                data["a"] = i.ToString();
                res = ClientAppAPIClient.GetInstance.Post("Default/Add", data);
                //Console.WriteLine(res);
            }
            Console.WriteLine("end");
            Console.WriteLine(sw.ElapsedMilliseconds);
            
            /**/

            //sw.Reset();
            //sw.Restart();
            //Console.WriteLine("start");
            //System.Threading.Tasks.Parallel.For(0, speed, (i) =>
            //{
            //    data["a"] = i.ToString();
            //    res = ClientAppAPIClient.GetInstance.Post("Default/Add", data);
            //    Console.WriteLine(res);

            //});
            //Console.WriteLine("end");
            //Console.WriteLine(sw.ElapsedMilliseconds);

            /**/

            res = ClientAppAPIClient2.GetInstance.Post("Default/Add", data);
            sw.Reset();
            sw.Restart();
            Console.WriteLine("start");
            for (var i = 0; i < speed; i++)
            {
                data["a"] = i.ToString();
                res = ClientAppAPIClient2.GetInstance.Post("Default/Add", data);
                //Console.WriteLine(res);
            }
            Console.WriteLine("end");
            Console.WriteLine(sw.ElapsedMilliseconds);

            /**/

            //sw.Reset();
            //sw.Restart();
            //Console.WriteLine("start");
            //System.Threading.Tasks.Parallel.For(0, speed, (i) =>
            //{
            //    data["a"] = i.ToString();
            //    res = ClientAppAPIClient2.GetInstance.Post("Default/Add", data);
            //    Console.WriteLine(res);

            //});
            //Console.WriteLine("end");
            //Console.WriteLine(sw.ElapsedMilliseconds);

            /**/

            //Console.WriteLine(res);

            Console.ReadLine();

        }
Exemplo n.º 33
0
 private static string Decrypt(string text, System.Security.Cryptography.TripleDESCryptoServiceProvider Des)
 {
     System.Security.Cryptography.ICryptoTransform desdencrypt = Des.CreateDecryptor();
     byte[] buff = Convert.FromBase64String(text);
     return(System.Text.ASCIIEncoding.ASCII.GetString(desdencrypt.TransformFinalBlock(buff, 0, buff.Length)));
 }
Exemplo n.º 34
0
 private static string EnCrypt(string strEnCrypt, string key)
 {
     try
     {
         byte[] keyArr;
         byte[] EnCryptArr = UTF8Encoding.UTF8.GetBytes(strEnCrypt);
         System.Security.Cryptography.MD5CryptoServiceProvider MD5Hash = new System.Security.Cryptography.MD5CryptoServiceProvider();
         keyArr = MD5Hash.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
         System.Security.Cryptography.TripleDESCryptoServiceProvider tripDes = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
         tripDes.Key = keyArr;
         tripDes.Mode = System.Security.Cryptography.CipherMode.ECB;
         tripDes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
         System.Security.Cryptography.ICryptoTransform transform = tripDes.CreateEncryptor();
         byte[] arrResult = transform.TransformFinalBlock(EnCryptArr, 0, EnCryptArr.Length);
         return Convert.ToBase64String(arrResult, 0, arrResult.Length);
     }
     catch (Exception ex) { }
     return string.Empty;
 }
Exemplo n.º 35
0
        /// <summary>
        /// Decrypt the specified string using the System.Security.Cryptography.TripleDESCryptoServiceProvider cryptographic
        /// service provider. The secret key used in the decryption is specified in the encryptionKey configuration setting.
        /// </summary>
        /// <param name="encryptedText">A string to be decrypted. The encrypted string should have been encrypted using the
        /// Encrypt function in this class. If the value is null or empty, the return value is equal to String.Empty.</param>
        /// <returns>
        /// Returns the original, unencrypted string contained in the encryptedText parameter.
        /// </returns>
        /// <exception cref="System.FormatException">Thrown when the text cannot be decrypted.</exception>
        public static string Decrypt(string encryptedText)
        {
            if (String.IsNullOrEmpty(encryptedText))
                return String.Empty;

            // Get the byte code of the string
            byte[] toEncryptArray = Convert.FromBase64String(encryptedText);

            using (System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider())
            {
                // Set the secret key for the tripleDES algorithm.
                tdes.Key = EncryptionKey;

                // Mode of operation. there are other 4 modes. We choose ECB(Electronic code Book)
                tdes.Mode = System.Security.Cryptography.CipherMode.ECB;

                // Padding mode(if any extra byte added)
                tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

                System.Security.Cryptography.ICryptoTransform cTransform = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                // Release resources held by TripleDes Encryptor
                tdes.Clear();

                // Return the Clear decrypted TEXT
                return System.Text.Encoding.UTF8.GetString(resultArray);
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Encrypt the specified string using the System.Security.Cryptography.TripleDESCryptoServiceProvider cryptographic
        /// service provider. The secret key used in the encryption is specified in the encryptionKey configuration setting.
        /// The encrypted string can be decrypted to its original string using the Decrypt function in this class.
        /// </summary>
        /// <param name="plainText">A plain text string to be encrypted. If the value is null or empty, the return value is
        /// equal to String.Empty.</param>
        /// <returns>Returns an encrypted version of the plainText parameter.</returns>
        public static string Encrypt(string plainText)
        {
            if (String.IsNullOrEmpty(plainText))
                return String.Empty;

            // This method (and the Decrypt method) inspired from Code Project.
            // http://www.codeproject.com/useritems/Cryptography.asp
            byte[] stringToEncryptArray = System.Text.Encoding.UTF8.GetBytes(plainText);

            using (System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider())
            {
                // Set the secret key for the tripleDES algorithm
                byte[] keyArray = EncryptionKey;
                tdes.Key = keyArray;

                // Mode of operation. there are other 4 modes. We choose ECB (Electronic code Book)
                tdes.Mode = System.Security.Cryptography.CipherMode.ECB;

                //padding mode(if any extra byte added)
                tdes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

                // Transform the specified region of bytes array to resultArray
                System.Security.Cryptography.ICryptoTransform cTransform = tdes.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(stringToEncryptArray, 0, stringToEncryptArray.Length);

                // Release resources held by TripleDes Encryptor
                tdes.Clear();

                // Return the encrypted data into unreadable string format
                return Convert.ToBase64String(resultArray);
            }
        }
Exemplo n.º 37
0
        public static XmlDocument DecryptXml(XmlDocument cipherDoc)
        {
            SecConvObj = null;
            if (DecObj == null)
            {
                return(cipherDoc);                //no keys to decrypt with
            }
            XmlElement envelope = cipherDoc.DocumentElement;

            //add namespace
            //XmlAttribute xenc = xd.CreateAttribute(Pre.xmlns, Pre.xenc, Ns.xmlns);
            //xenc.Value = Ns.xenc;
            //envelope.Attributes.Append(xenc);

            XmlElement headerOrBody = (XmlElement)envelope.ChildNodes[0];
            XmlElement header       = null;
            XmlElement body         = null;

            if (headerOrBody.LocalName == Elem.Header)
            {
                header = (XmlElement)envelope.ChildNodes[0];
                body   = (XmlElement)envelope.ChildNodes[1];
            }
            else             //no header
            {
                body = (XmlElement)envelope.ChildNodes[0];
            }

            string encKeyMethod = null;

            byte [] baEncKey = null;
            string  encKeyId = null;
            //UsernameToken encryption
            XmlElement nonce   = null;
            XmlElement created = null;

            //search for Security in Header, remove MustUnderstand
            if (header != null)
            {
                XmlElement securityElem = LameXpath.SelectSingleNode(header, Elem.Security);
                if (securityElem != null)
                {
                    XmlAttribute mustUndAtt = securityElem.Attributes[Attrib.mustUnderstand, Ns.soap];
                    if (mustUndAtt != null)
                    {
                        mustUndAtt.Value = "0";
                    }
                    //securityElem.ParentNode.RemoveChild(securityElem);

                    XmlElement encKeyElem = LameXpath.SelectSingleNode(securityElem, Elem.EncryptedKey);
                    if (encKeyElem != null)
                    {
                        XmlElement encMethodElem = LameXpath.SelectSingleNode(encKeyElem, Elem.EncryptionMethod);
                        if (encMethodElem != null)
                        {
                            encKeyMethod = encMethodElem.Attributes[Attrib.Algorithm].Value;
                        }
                        //ignore KeyInfo, use SecurityTokenReference instead

                        XmlElement cipherValElem = LameXpath.SelectSingleNode(securityElem, Elem.CipherValue);
                        if (cipherValElem != null)
                        {
                            baEncKey = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(cipherValElem.InnerText);
                        }
                    }

                    XmlElement refListElem = LameXpath.SelectSingleNode(securityElem, Elem.ReferenceList);
                    if (refListElem != null)
                    {
                        //ignore refList, just do straight to encData
                    }
                    XmlElement keyIdElem = LameXpath.SelectSingleNode(securityElem, Elem.KeyIdentifier);
                    if (keyIdElem != null)                    //get keyId
                    {
                        string valueType = keyIdElem.Attributes[Attrib.ValueType].Value;
                        //"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier
                        if (valueType.EndsWith("#X509SubjectKeyIdentifier") == false && valueType != "wsse:X509v3")
                        {
                            throw new Exception("only support X.509v3 certificates");
                        }
                        encKeyId = keyIdElem.InnerText;
                    }
                    XmlElement refElem = LameXpath.SelectSingleNode(securityElem, Elem.Reference);
                    if (refElem != null)                    //get keyUri
                    {
                        string refUri = refElem.Attributes[Attrib.URI].Value;
                    }
                    XmlElement userTokElem = LameXpath.SelectSingleNode(securityElem, Elem.UsernameToken);
                    if (userTokElem != null)
                    {
                        nonce   = LameXpath.SelectSingleNode(userTokElem, Elem.Nonce);
                        created = LameXpath.SelectSingleNode(userTokElem, Elem.Created);
                    }
                }
                //end header processing
            }

            byte [] baPlainKey = null;
            if (encKeyMethod != null)            //decrypt key, assume RSA
            {
                baPlainKey = DecObj.RSACSP.Decrypt(baEncKey, false);
                KeyExchangeFormatter fmt = DecObj.SymmAlg.KeyExchangeFormatter;
                DecObj.SymmAlg.Key.Key = baPlainKey;
            }
            //UsernameToken decryption
            if (DecObj.ClearPassword != null)
            {
                //use XmlSigHandler values, because will more than likely be signing
                int numKeyBytes = DecObj.SymmAlg.Key.Key.Length;
                if (nonce == null || created == null)
                {
                    baPlainKey = P_SHA1.DeriveKey(DecObj.ClearPassword, XmlSigHandler.StrKeyLabel, DecObj.UserTok.Nonce.Text, DecObj.UserTok.Created, numKeyBytes);
                }
                else
                {
                    baPlainKey = P_SHA1.DeriveKey(DecObj.ClearPassword, XmlSigHandler.StrKeyLabel, nonce.InnerText, created.InnerText, numKeyBytes);
                }
                DecObj.SymmAlg.Key.Key = baPlainKey;
            }

            //TODO EncryptedKey in body?, multiple EncryptedData in body

            string     encBodMethod = null;
            string     keyName      = null;
            XmlElement cipherElem   = LameXpath.SelectSingleNode(cipherDoc, Elem.EncryptedData);

            //if(cipherElem == null)
            //	return cipherDoc; //nothing to decrypt
            if (cipherElem != null)
            {
                XmlElement encMethodElemBod = LameXpath.SelectSingleNode(cipherElem, Elem.EncryptionMethod);
                if (encMethodElemBod != null)
                {
                    encBodMethod = encMethodElemBod.Attributes[Attrib.Algorithm].Value;
                    if (encBodMethod == Alg.aes128cbc)
                    {
                        if (DecObj.SymmAlg is TripleDES)
                        {
                            throw new Exception("device expects TripleDES, not AES");
                        }
                    }
                    if (encBodMethod == Alg.tripledesCbc)
                    {
                        if ((DecObj.SymmAlg is TripleDES) == false)
                        {
                            throw new Exception("device expects AES, not TripleDES");
                        }
                    }
                }
                XmlElement keyNameElem = LameXpath.SelectSingleNode(cipherElem, Elem.KeyName);
                if (keyNameElem != null)
                {
                    keyName = keyNameElem.InnerText;
                }

                XmlElement cipherValueElem = LameXpath.SelectSingleNode(cipherElem, Elem.CipherValue);
                byte[]     baCipher        = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(cipherValueElem.InnerText);

                //should have encMethod, key, and cipherData now

                System.Security.Cryptography.SymmetricAlgorithm sa = DecObj.SymmAlg.Key;
                byte[] baClear = DecObj.SymmAlg.EncryptionFormatter.Decrypt(baCipher);

                /*
                 * PlainTextType ptType = PlainTextType.Content; //default
                 * if(cipherElem.Attributes["Type"] != null)
                 * {
                 *      string strType = cipherElem.Attributes["Type"].Value;
                 *      if(strType == "http://www.w3.org/2001/04/xmlenc#Element")
                 *              ptType = PlainTextType.Element;
                 * }
                 */

                string strClear = OpenNETCF.Security.Cryptography.Internal.Format.GetString(baClear); //for debugging
                cipherElem.ParentNode.InnerXml = strClear;
            }

            //MOD for SecureConversation
            //XmlElement rstrElem = LameXpath.SelectSingleNode(body, Elem.RequestSecurityToken); //temp for testing
            XmlElement rstrElem = LameXpath.SelectSingleNode(body, Elem.RequestSecurityTokenResponse);

            if (rstrElem != null)
            {
                SecConvObj = new SecConvObject();
                //<TokenType/>
                XmlElement ttElem = LameXpath.SelectSingleNode(rstrElem, Elem.TokenType);
                if (ttElem != null)
                {
                    SecConvObj.tokenType           = new TokenType();
                    SecConvObj.tokenType.InnerText = ttElem.InnerText;
                }
                //ignore <AppliesTo/> for now

                //Entropy
                XmlElement entropyElem = LameXpath.SelectSingleNode(rstrElem, Elem.Entropy);
                if (entropyElem != null)
                {
                    XmlElement encKeyElem = LameXpath.SelectSingleNode(entropyElem, Elem.EncryptedKey);
                    if (encKeyElem != null)
                    {
                        XmlElement cipherValElem = LameXpath.SelectSingleNode(encKeyElem, Elem.CipherValue);
                        if (cipherValElem != null)
                        {
                            baEncKey = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(cipherValElem.InnerText);
                        }
                        XmlElement encMethodElem = LameXpath.SelectSingleNode(encKeyElem, Elem.EncryptionMethod);
                        if (encMethodElem != null)
                        {
                            encKeyMethod = encMethodElem.Attributes[Attrib.Algorithm].Value;
                            if (encKeyMethod == Alg.kwTripledes)
                            {
                                throw new Exception("return Entropy with kw-TripleDes is not supported");
                            }
                            if (encKeyMethod == Alg.kwAes128)
                            {
                                XmlElement keyNameElem = LameXpath.SelectSingleNode(encKeyElem, Elem.KeyName);
                                if (keyNameElem != null)
                                {
                                    keyName = keyNameElem.InnerText;
                                }
                                if (DecObj.SymmAlg.Key is System.Security.Cryptography.TripleDES)
                                {
                                    throw new Exception("device expects TripleDES, not AES128");
                                }
                                //the request entropy is encrypted with RSA
                                //it passes a symmetric key
                                //the response is encrypted with kw-aes128
                                //the key for the kw-aes128 seems to be the symm key passed by RSA?
                                System.Security.Cryptography.SymmetricAlgorithm sa = DecObj.keyWrap;
                                //key should have already been set
                                byte[] unwrappedKey = Decrypt(sa, baEncKey);
                                SecConvObj.entropyKey = unwrappedKey;
                            }
                            if (encKeyMethod == Alg.rsa15)
                            {
                                //TODO - this scenario is not expected?
                                XmlElement keyIdElem = LameXpath.SelectSingleNode(encKeyElem, Elem.KeyIdentifier);
                                if (keyIdElem != null)
                                {
                                    keyName = keyIdElem.InnerText;
                                }
                                baPlainKey            = DecObj.RSACSP.DecryptValue(baEncKey);
                                SecConvObj.secConvKey = baPlainKey;
                                //went from 128 bytes to 16 decrypted - AES?
                                //DecObj.SymmAlg.Key.Key = baPlainKey;
                            }
                        }
                        XmlElement carriedKeyNameElem = LameXpath.SelectSingleNode(encKeyElem, Elem.CarriedKeyName);
                        if (carriedKeyNameElem != null)
                        {
                            keyName = carriedKeyNameElem.InnerText;
                        }
                    }
                }

                //RST
                XmlElement rstElem = LameXpath.SelectSingleNode(rstrElem, Elem.RequestedSecurityToken);
                if (rstElem != null)
                {
                    SecConvObj.requestedSecurityToken = rstElem;
                }
                //RPT
                XmlElement rptElem = LameXpath.SelectSingleNode(rstrElem, Elem.RequestedProofToken);
                if (rptElem != null)
                {
                    SecConvObj.requestedProofToken = rptElem;

                    //figure out if key is computed
                    //TODO use this later on
                    bool       computed    = false;
                    XmlElement compKeyElem = LameXpath.SelectSingleNode(rptElem, Elem.ComputedKey);
                    if (compKeyElem != null)
                    {
                        computed = true;
                    }
                    if (computed == true)
                    {
                        //throw new Exception("not handling computed return keys yet");
                        byte [] entropy1        = DecObj.keyWrap.Key;
                        byte [] entropy2        = SecConvObj.entropyKey;
                        byte [] concatEntropies = new byte[entropy1.Length + entropy2.Length];
                        Array.Copy(entropy1, 0, concatEntropies, 0, entropy1.Length);
                        Array.Copy(entropy2, 0, concatEntropies, entropy1.Length, entropy2.Length);
                        SecConvObj.secConvKey = P_SHA1.DeriveKey(entropy1, entropy2, XmlSigHandler.NumKeyBytes);
                    }

                    XmlElement encMethodElemBod = LameXpath.SelectSingleNode(rptElem, Elem.EncryptionMethod);
                    if (encMethodElemBod != null)
                    {
                        encBodMethod = encMethodElemBod.Attributes[Attrib.Algorithm].Value;
                        if (encBodMethod == Alg.kwAes128)
                        {
                            //throw new Exception("only supports TripleDes, no AES on device");
                            XmlElement cvElem = LameXpath.SelectSingleNode(rptElem, Elem.CipherValue);
                            //byte [] baPKey = null;
                            if (cvElem != null)
                            {
                                byte[] baCipher = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(cvElem.InnerText);

                                int    numKeyBytes = DecObj.SymmAlg.Key.Key.Length;
                                string tempLabel   = XmlSigHandler.StrKeyLabel;                               //WS-Security

                                baPlainKey = P_SHA1.DeriveKey(DecObj.ClearPassword, tempLabel, nonce.InnerText, created.InnerText, numKeyBytes);

                                //TODO make TripleDES below work like this too - common codebase
                                System.Security.Cryptography.SymmetricAlgorithm sa = DecObj.keyWrap;
                                sa.Key = baPlainKey;
                                byte[] unwrappedKey = Decrypt(sa, baCipher);

                                SecConvObj.secConvKey = unwrappedKey;
                            }
                        }
                        else if (encBodMethod == Alg.kwTripledes)
                        {
                            XmlElement cvElem = LameXpath.SelectSingleNode(rptElem, Elem.CipherValue);
                            //byte [] baPKey = null;
                            if (cvElem != null)
                            {
                                byte[] baCipher = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(cvElem.InnerText);

                                int    numKeyBytes = DecObj.SymmAlg.Key.Key.Length;
                                string tempLabel   = XmlSigHandler.StrKeyLabel;                               //WS-Security
                                //string tempLabel = "WS-SecureConversation";

                                baPlainKey = P_SHA1.DeriveKey(DecObj.ClearPassword, tempLabel, nonce.InnerText, created.InnerText, numKeyBytes);

                                //TODO make this work with KeyWrap interface
                                //SymmetricAlgorithm sa = DecObj.SymmAlg;
                                System.Security.Cryptography.TripleDESCryptoServiceProvider sa = (System.Security.Cryptography.TripleDESCryptoServiceProvider)DecObj.SymmAlg.Key;
                                sa.Key = baPlainKey;
                                TripleDesKeyWrap tdkw         = new TripleDesKeyWrap(sa);
                                byte []          unwrappedKey = tdkw.DecryptValue(baCipher);

                                SecConvObj.secConvKey = unwrappedKey;
                            }
                        }
                        else                         //http://www.w3.org/2001/04/xmlenc#rsa-1_5
                        {
                            XmlElement cvElem = LameXpath.SelectSingleNode(rptElem, Elem.CipherValue);
                            byte []    baPKey = null;
                            if (cvElem != null)
                            {
                                byte[] baEKey = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(cvElem.InnerText);
                                baPKey = DecObj.RSACSP.DecryptValue(baEKey);
                                SecConvObj.secConvKey = baPKey;
                            }
                        }
                    }
                    //else
                    //{
                    //	throw new Exception("EncryptionMethod not specified");
                    //}
                }
                //ignore <LifeTime/> for now
            }

            DecObj = null;
            return(cipherDoc);
        }