Clear() public method

public Clear ( ) : void
return void
Esempio n. 1
0
        public byte[] Encrypt(byte[] srcBuffer)
        {
            try
            {
                byte[]       buffer    = srcBuffer;       // srcStream.GetBuffer();
                int          bufferlen = buffer.Length;
                MemoryStream mStream   = new MemoryStream();
                CryptoStream cStream   = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write);

                cStream.Write(buffer, 0, bufferlen);
                cStream.FlushFinalBlock();

                byte[] result = mStream.ToArray();
                cStream.Close();
                des.Clear();
                return(result);
            }
            catch (System.Exception ex)
            {
#if DEBUG
                throw ex;
#else
                log.Error(ex.ToString());
                return(null);
#endif
            }
        }
Esempio n. 2
0
        public byte[] Encrypt(byte[] srcBuffer)
        {
            try
            {
                byte[] buffer    = srcBuffer;// srcStream.GetBuffer();
                int    bufferlen = buffer.Length;

                lock (this)
                {
                    byte[] result = encryptor.TransformFinalBlock(srcBuffer, 0, bufferlen);

                    aes.Clear();


                    return(result);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                throw ex;
#else
                log.Error(ex.ToString());
                return(null);
#endif
            }
        }
        private byte[] TransformByCryptoStream(SymmetricAlgorithm algorithm, byte[] bytes, bool encrypt)
        {
            algorithm.Clear();

              if (encrypt)
            return TransformByCryptoStream(algorithm.CreateEncryptor(), bytes);
              else
            return TransformByCryptoStream(algorithm.CreateDecryptor(), bytes);
        }
Esempio n. 4
0
        // All symmetric algorithms inherit from the SymmetricAlgorithm base class, to which we can cast from the original crypto service provider
        private byte[] SymmetricEncrypt(SymmetricAlgorithm Provider, byte[] plainText, string key, int keySize)
        {
            byte[] ivBytes = null;
            switch (keySize / 8)
            {
                //Determine which initialization vector to use
                case 8:
                    ivBytes = IV_8;
                    break;
                case 16:
                    ivBytes = IV_16;
                    break;
                case 24:
                    ivBytes = IV_24;
                    break;
                case 32:
                    ivBytes = IV_32;
                    break;
                default:
                    break;
                //TODO: Throw an error because an invalid key length has been passed
            }

            Provider.KeySize = keySize;

            //Generate a secure key based on the original password by using SALT
            byte[] keyStream = DerivePassword(key, keySize / 8);

            //Initialize our encryptor object
            ICryptoTransform trans = Provider.CreateEncryptor(keyStream, ivBytes);

            //Perform the encryption on the textStream byte array
            byte[] result = trans.TransformFinalBlock(plainText, 0, plainText.GetLength(0));

            //Release cryptographic resources
            Provider.Clear();
            trans.Dispose();

            return result;
        }
Esempio n. 5
0
        //All symmetric algorithms inherit from the SymmetricAlgorithm base class, to which we can cast from the original crypto service provider
        public byte[] SymmetricDecrypt(SymmetricAlgorithm Provider, byte[] encByte, string key, int keySize)
        {
            byte[] ivBytes = null;
            switch (keySize / 8)
            {
                //Determine which initialization vector to use
                case 8:
                    ivBytes = IV_8;
                    break;
                case 16:
                    ivBytes = IV_16;
                    break;
                case 24:
                    ivBytes = IV_24;
                    break;
                case 32:
                    ivBytes = IV_32;
                    break;
                default:
                    break;
                //TODO: Throw an error because an invalid key length has been passed
            }

            //Generate a secure key based on the original password by using SALT
            byte[] keyStream = DerivePassword(key, keySize / 8);

            //Convert our hex-encoded cipher text to a byte array
            byte[] textStream = encByte;
            //HexToBytes(encText)
            Provider.KeySize = keySize;

            //Initialize our decryptor object
            ICryptoTransform trans = Provider.CreateDecryptor(keyStream, ivBytes);

            //Initialize the result stream
            byte[] result = null;

            try
            {
                result = trans.TransformFinalBlock(textStream, 0, textStream.GetLength(0));
            }
            catch (Exception ex)
            {
                throw new System.Security.Cryptography.CryptographicException("The following exception occurred during decryption: " + ex.Message);
            }
            finally
            {
                Provider.Clear();
                trans.Dispose();
            }

            return result;
        }
        protected static byte[] Encrypt(byte[] plainText, SymmetricAlgorithm encryptionAlgorithm, string base64Key, string base64IV)
        {
            if (base64Key == null || base64Key.Length == 0)
            {
              throw new Exception("Empty Key");
            }
            if (base64IV == null || base64IV.Length == 0)
            {
              throw new Exception("Empty Initialization Vector");
            }
            encryptionAlgorithm.Key = Convert.FromBase64String(base64Key);
            encryptionAlgorithm.IV = Convert.FromBase64String(base64IV);

            byte[] cipherValue = null;
            byte[] plainValue = plainText;

            MemoryStream memStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memStream, encryptionAlgorithm.CreateEncryptor(), CryptoStreamMode.Write);
            try
            {
              // Write the encrypted information
              cryptoStream.Write(plainValue, 0, plainValue.Length);
              cryptoStream.Flush();
              cryptoStream.FlushFinalBlock();

              // Get the encrypted stream
              cipherValue = memStream.ToArray();

            }
            finally
            {
              // Clear the arrays
              if (plainValue != null)
              {
            Array.Clear(plainValue, 0, plainValue.Length);
              }
              memStream.Close();
              cryptoStream.Close();
              encryptionAlgorithm.Clear();
              ((IDisposable)encryptionAlgorithm).Dispose();
            }

            return cipherValue;
        }
        protected static byte[] Decrypt(byte[] cipherText, SymmetricAlgorithm encryptionAlgorithm, string base64Key, string base64IV)
        {
            if (base64Key == null || base64Key.Length == 0)
            {
              throw new Exception("Empty Key");
            }
            if (base64IV == null || base64IV.Length == 0)
            {
              throw new Exception("Empty Initialization Vector");
            }
            encryptionAlgorithm.Key = Convert.FromBase64String(base64Key);
            encryptionAlgorithm.IV = Convert.FromBase64String(base64IV);

            byte[] cipherValue = cipherText;
            byte[] plainValue = new byte[cipherValue.Length + 1];

            MemoryStream memStream = new MemoryStream(cipherValue);
            CryptoStream cryptoStream = new CryptoStream(memStream, encryptionAlgorithm.CreateDecryptor(), CryptoStreamMode.Read);
            try
            {
              // Decrypt the data
              cryptoStream.Read(plainValue, 0, plainValue.Length);

            }
            finally
            {
              // Clear the arrays
              if (cipherValue != null)
              {
            Array.Clear(cipherValue, 0, cipherValue.Length);
              }
              memStream.Close();
              //Flush the stream buffer
              cryptoStream.Close();
              encryptionAlgorithm.Clear();
              ((IDisposable)encryptionAlgorithm).Dispose();
            }

            return plainValue;
        }
        /// <summary>
        /// Creates a random IV value appropriate for
        /// the encryption algorithm
        /// </summary>
        /// <param name="encryptionAlgorithm">Instance of SymmetricAlgorithm used to create the IV</param>
        /// <returns>Base64 encoded byte array containing the IV value</returns>
        protected static string CreateBase64IV(SymmetricAlgorithm encryptionAlgorithm)
        {
            byte[] iv = null;
            try
            {
              encryptionAlgorithm.GenerateIV();
              iv = encryptionAlgorithm.IV;

            }
            finally
            {
              encryptionAlgorithm.Clear();
              ((IDisposable)encryptionAlgorithm).Dispose();
            }
            return Convert.ToBase64String(iv);
        }
        /// <summary>
        /// Creates a random key value appropriate for
        /// the encryption algorithm
        /// </summary>
        /// <param name="encryptionAlgorithm">Instance of SymmetricAlgorithm used to create the key</param>
        /// <returns>Base64 encoded byte array containing the key value</returns>
        public static string CreateBase64Key(SymmetricAlgorithm encryptionAlgorithm)
        {
            byte[] key = null;
            try
            {
              encryptionAlgorithm.GenerateKey();
              key = encryptionAlgorithm.Key;

            }
            finally
            {
              encryptionAlgorithm.Clear();
              ((IDisposable)encryptionAlgorithm).Dispose();
            }
            return Convert.ToBase64String(key);
        }
Esempio n. 10
0
        /// <summary>
        ///Decrypt an array of bytes using key and insertion vector (also called block size).  NOTE: This is the base
        /// method for decryption methods.  Other decryption methods are convenience overloads
        /// </summary>
        /// <param name="encryptedBytes">Non-null,non-zero length array of bytes to decrypt</param>
        /// <param name="keyBytes">Key for encryption algorithm. Must be 126, 128, or 256 bits (16, 24, 32 bytes) </param>
        /// <param name="ivBytes">Insertion vector (also called block size). Must be 126, 128, or 256 bits (16, 24, 32 bytes)</param>
        /// <param name="encryptor">.Net library that will perform actual decryption</param>
        /// <returns>An encrypted byte array</returns>
        private byte[] decode(SymmetricAlgorithm encryptor, byte[] encryptedBytes, byte[] keyBytes, byte[] ivBytes)
        {
            // Create a MemoryStream that is going to accept the
            // decrypted bytes 
            using (MemoryStream ms = new MemoryStream())
            {

                // Create a symmetric algorithm. 
                // We are going to use Rijndael because it is strong and
                // available on all platforms. 
                // You can use other algorithms, to do so substitute the next
                // line with something like 
                //     TripleDES alg = TripleDES.Create(); 
               
                try
                {
                    // explicitly set block sizes since
                    // keys may not be default lengths
                    // Legal values are:
                    //      Key Size:   128, 192, 256
                    //      Block Size: 128, 192, 256
                    //      Bytes        16,  24,  32
                    encryptor.BlockSize = ivBytes.Length * 8;
                    encryptor.KeySize = keyBytes.Length * 8;

                    // Now set the key and the IV. 
                    // We need the IV (Initialization Vector) because the algorithm
                    // is operating in its default 
                    // mode called CBC (Cipher Block Chaining). The IV is XORed with
                    // the first block (8 byte) 
                    // of the data after it is decrypted, and then each decrypted
                    // block is XORed with the previous 
                    // cipher block. This is done to make encryption more secure. 
                    // There is also a mode called ECB which does not need an IV,
                    // but it is much less secure. 
                    encryptor.Key = keyBytes;
                    encryptor.IV = ivBytes;

                    // Create a CryptoStream through which we are going to be
                    // pumping our data. 
                    // CryptoStreamMode.Write means that we are going to be
                    // writing data to the stream 
                    // and the output will be written in the MemoryStream
                    // we have provided. 
                    using (CryptoStream cs = new CryptoStream(ms,
                        encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {

                        // Write the data and make it do the decryption 
                        cs.Write(encryptedBytes, 0, encryptedBytes.Length);

                        // Close the crypto stream (or do FlushFinalBlock). 
                        // This will tell it that we have done our decryption
                        // and there is no more data coming in, 
                        // and it is now a good time to remove the padding
                        // and finalize the decryption process. 
                        cs.Close();

                        // Now get the decrypted data from the MemoryStream. 
                        // Some people make a mistake of using GetBuffer() here,
                        // which is not the right way. 
                        byte[] decryptedData = ms.ToArray();

                        return decryptedData;
                    }
                }
                finally
                {
                    if (encryptor != null)
                    {
                        encryptor.Clear(); //remove any resources this might have
                    }
                }
            } //using memory stream
        }
Esempio n. 11
0
        /// <summary> Symmetrical function to Decrypt
        /// </summary>
        /// <param name="provider">Type of provider</param>
        /// <param name="encText">To be decrypted content</param>
        /// <param name="key">Type key</param>
        /// <param name="keySize">Size of key</param>
        /// <returns></returns>
        private byte[] SymmetricDecrypt(SymmetricAlgorithm provider, string encText, string key, int keySize)
        {
            //All symmetric algorithms inherit from the SymmetricAlgorithm base class, to which we can cast from the original crypto service provider
            byte[] ivBytes = GetInitializationVector(keySize);

            //Generate a secure key based on the original password by using SALT
            byte[] keyStream = DerivePassword(key, keySize / 8);

            //Convert our hex-encoded cipher text to a byte array
            byte[] textStream = HexToBytes(encText);
            provider.KeySize = keySize;

            //Initialize our decryptor object
            ICryptoTransform trans = provider.CreateDecryptor(keyStream, ivBytes);

            //Initialize the result stream
            byte[] result = null;
            try
            {
                //Perform the decryption on the textStream byte array
                result = trans.TransformFinalBlock(textStream, 0, textStream.Length);
            }
            catch (Exception ex)
            {

                throw new System.Security.Cryptography.CryptographicException("The following exception occurred during decryption: " + ex.Message);
            }
            finally
            {
                //Release cryptographic resources
                provider.Clear();
                trans.Dispose();
            }
            return result;
        }
Esempio n. 12
0
        /// <summary> Symmetrical function to Encrypt
        /// </summary>
        /// <param name="provider">Type of provider</param>
        /// <param name="encText">To be encrypted content</param>
        /// <param name="key">Type key</param>
        /// <param name="keySize">Size of key</param>
        /// <returns>Array of byte</returns>
        private byte[] SymmetricEncrypt(SymmetricAlgorithm provider, byte[] plainText, string key, int keySize)
        {
            //All symmetric algorithms inherit from the SymmetricAlgorithm base class, to which we can cast from the original crypto service provider
            byte[] ivBytes = GetInitializationVector(keySize);
            provider.KeySize = keySize;

            //Generate a secure key based on the original password by using SALT
            byte[] keyStream = DerivePassword(key, keySize / 8);

            //Initialize our encryptor object
            ICryptoTransform trans = provider.CreateEncryptor(keyStream, ivBytes);

            //Perform the encryption on the textStream byte array
            byte[] result = trans.TransformFinalBlock(plainText, 0, plainText.GetLength(0));

            //Release cryptographic resources
            provider.Clear();
            trans.Dispose();

            return result;
        }
Esempio n. 13
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Doc"></param>
        /// <param name="ElementName">Ruta completa del elemento a encriptar
        /// Ejemplos:
        /// <example>
        /// Encripta el precio los libros cuyo precio es mayor a 35
        /// /bookstore/book[price>35]/price 
        /// 
        /// Busca el grupos "ValidationExceptionMessage" y dentro de este la clave con nombre "MaxLenghtField" 
        ///         "/ConfigurationFile/Groups/Group[@name='ValidationExceptionMessage']/Keys/Key[@name='MaxLenghtField']"
        ///         
        /// 
        /// "//EXAMPLE/CUSTOMER[substring(@type,1,2) ='DE']"
        /// "//EXAMPLE/CUSTOMER[contains(@type,'DECEA')]"
        /// </example>
        /// </param>
        /// <param name="Key"></param>
        public static string Encrypt(string xml, string elementPath, SymmetricAlgorithm symmetricAlgorithm)
        {

            // Check the arguments.  
            if (string.IsNullOrEmpty(xml))
                throw new ArgumentNullException("xml");
            if (string.IsNullOrEmpty(elementPath))
                throw new ArgumentNullException("elementPath");
            if (symmetricAlgorithm == null)
                throw new ArgumentNullException("SymmetricAlgorithm");


            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(xml);

            ///bookstore/book[price>35]/price 
            /// "/ConfigurationFile/Groups/Group[@name='ValidationExceptionMessage']/Keys/Key[@name='MaxLenghtField']"
            XmlElement elementToEncrypt = xmlDoc.SelectSingleNode(elementPath) as XmlElement;

            // Throw an XmlException if the element was not found.
            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");

            }


            //////////////////////////////////////////////////
            // Creo una instancia de EncryptedXml y la uso 
            // para encriptar XmlElement con lka clave simetrica
            //////////////////////////////////////////////////
            EncryptedXml eXml = new EncryptedXml();

            
            byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, symmetricAlgorithm, false);

            // Construct an EncryptedData object and populate
            // it with the desired encryption information.
            EncryptedData edElement = new EncryptedData();
            edElement.Type = EncryptedXml.XmlEncElementUrl;
            edElement.EncryptionMethod = GetEncrypTionMethod(symmetricAlgorithm);

            //// Add the encrypted element data to the EncryptedData object.
            edElement.CipherData.CipherValue = encryptedElement;

            // Create a new KeyInfo element.
            edElement.KeyInfo = new KeyInfo();


            //// Encrypt the session key and add it to an EncryptedKey element.
            //EncryptedKey ek = new EncryptedKey();


            //// Create a new KeyInfoName element.
            //KeyInfoName kin = new KeyInfoName();

            //// Specify a name for the key.
            //kin.Value = KeyName;

            //// Add the KeyInfoName element to the 
            //// EncryptedKey object.
            //ek.KeyInfo.AddClause(kin);

            // Add the encrypted key to the 
            // EncryptedData object.

            //edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));




            // Replace the element from the original XmlDocument   object with the EncryptedData element.
            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
            symmetricAlgorithm.Clear();
            xml = xmlDoc.InnerXml;
            xmlDoc = null;
            return xml;
        }
Esempio n. 14
0
        public static string Decrypt(string xmlEncrypted, string elementPath, SymmetricAlgorithm symmetricAlgorithm)
        {

            // Check the arguments.  
            if (string.IsNullOrEmpty(xmlEncrypted))
                throw new ArgumentNullException("xml");
            if (string.IsNullOrEmpty(elementPath))
                throw new ArgumentNullException("elementPath");
            if (symmetricAlgorithm == null)
                throw new ArgumentNullException("SymmetricAlgorithm ");


            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(xmlEncrypted);


            // Find the EncryptedData element in the XmlDocument.
            
            XmlNodeList encryptedElementxmlDoc = xmlDoc.GetElementsByTagName("EncryptedData");

            // If the EncryptedData element was not found, throw an exception.
            if (encryptedElementxmlDoc == null)
            {
                throw new XmlException("The EncryptedData element was not found.");
            }
            EncryptedData edElement;
            EncryptedXml exml = new EncryptedXml(xmlDoc);
            // Add a key-name mapping.
            // This method can only decrypt documents
            // that present the specified key name.
            exml.AddKeyNameMapping("", symmetricAlgorithm);


            exml.DecryptDocument();
      
            //foreach (XmlNode node in encryptedElementxmlDoc)
            //{


            //    // Create an EncryptedData object and populate it.
            //    edElement = new EncryptedData();
            //    edElement.LoadXml(node as XmlElement);
            //    exml = new EncryptedXml();

            //    exml.DecryptDocument();

            //    //// Decrypt the element using the symmetric key.
            //    //byte[] rgbOutput = exml.DecryptData(edElement, symmetricAlgorithm);

            //    //// Replace the encryptedData element with the plaintext XML element.
            //    //exml.ReplaceData(node as XmlElement, rgbOutput);
            //}



            symmetricAlgorithm.Clear();
            xmlEncrypted = xmlDoc.InnerXml;
            xmlDoc = null;
            return xmlEncrypted;
        }