当前位置: 首页>>代码示例>>C#>>正文


C# SymmetricAlgorithm.Clear方法代码示例

本文整理汇总了C#中System.Security.Cryptography.SymmetricAlgorithm.Clear方法的典型用法代码示例。如果您正苦于以下问题:C# SymmetricAlgorithm.Clear方法的具体用法?C# SymmetricAlgorithm.Clear怎么用?C# SymmetricAlgorithm.Clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Security.Cryptography.SymmetricAlgorithm的用法示例。


在下文中一共展示了SymmetricAlgorithm.Clear方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TransformByCryptoStream

        private byte[] TransformByCryptoStream(SymmetricAlgorithm algorithm, byte[] bytes, bool encrypt)
        {
            algorithm.Clear();

              if (encrypt)
            return TransformByCryptoStream(algorithm.CreateEncryptor(), bytes);
              else
            return TransformByCryptoStream(algorithm.CreateDecryptor(), bytes);
        }
开发者ID:pengyancai,项目名称:cs-util,代码行数:9,代码来源:ICryptoTransformExtensions.cs

示例2: SymmetricEncrypt

        // 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;
        }
开发者ID:pmrenaud,项目名称:BlackCat,代码行数:41,代码来源:fileCrypto.cs

示例3: SymmetricDecrypt

        //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;
        }
开发者ID:pmrenaud,项目名称:BlackCat,代码行数:54,代码来源:fileCrypto.cs

示例4: Encrypt

        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;
        }
开发者ID:rockfordlhotka,项目名称:SerializationWrapper,代码行数:44,代码来源:CryptoWrapperBase.cs

示例5: Decrypt

        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;
        }
开发者ID:rockfordlhotka,项目名称:SerializationWrapper,代码行数:40,代码来源:CryptoWrapperBase.cs

示例6: CreateBase64IV

        /// <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);
        }
开发者ID:rockfordlhotka,项目名称:SerializationWrapper,代码行数:22,代码来源:CryptoWrapperBase.cs

示例7: CreateBase64Key

        /// <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);
        }
开发者ID:rockfordlhotka,项目名称:SerializationWrapper,代码行数:22,代码来源:CryptoWrapperBase.cs

示例8: decode

        /// <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
        }
开发者ID:drio4321,项目名称:ScrimpNet.Core,代码行数:84,代码来源:SymmetricEncoder.cs

示例9: SymmetricDecrypt

        /// <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;
        }
开发者ID:sidneylimafilho,项目名称:InfoControl,代码行数:42,代码来源:Cypher.cs

示例10: SymmetricEncrypt

        /// <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;
        }
开发者ID:sidneylimafilho,项目名称:InfoControl,代码行数:28,代码来源:Cypher.cs

示例11: Encrypt

        /// <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;
        }
开发者ID:spzenk,项目名称:sfdocsamples,代码行数:98,代码来源:Form1.cs

示例12: Decrypt

        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;
        }
开发者ID:spzenk,项目名称:sfdocsamples,代码行数:61,代码来源:Form1.cs


注:本文中的System.Security.Cryptography.SymmetricAlgorithm.Clear方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。