• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Cryptography.SymmetricAlgorithm类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



SymmetricAlgorithm类属于System.Security.Cryptography命名空间,在下文中一共展示了SymmetricAlgorithm类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: IsolatedStorageOfflineContext

        /// <summary>
        /// Constructor for the offline context which allows a symmetric encryption algorithm to be specified.
        /// </summary>
        /// <param name="schema">The schema that specifies the set of the collections for the context.</param>
        /// <param name="scopeName">The scope name used to identify the scope on the service.</param>
        /// <param name="cachePath">Path in isolated storage where the data will be stored.</param>
        /// <param name="uri">Uri of the scopeName.  Used to intialize the CacheController.</param>
        /// <param name="encryptionAlgorithm">The symmetric encryption algorithm to use for files on disk</param>
        /// <remarks>
        /// If the Uri specified is different from the one that is stored in the cache path, the
        /// Load method will throw an InvalidOperationException.
        /// </remarks>
        public IsolatedStorageOfflineContext(IsolatedStorageSchema schema, string scopeName, string cachePath,
            Uri uri, SymmetricAlgorithm encryptionAlgorithm)
        {
            if (schema == null)
            {
                throw new ArgumentNullException("schema");
            }

            if (string.IsNullOrEmpty(scopeName))
            {
                throw new ArgumentNullException("scopeName");
            }

            if (string.IsNullOrEmpty(cachePath))
            {
                throw new ArgumentNullException("cachePath");
            }

            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            _isDisposed = false;

            _schema = schema;
            _scopeUri = uri;
            _scopeName = scopeName;
            _cachePath = cachePath;
            _storageHandler = new SQLiteStorageHandler(this, schema, cachePath, encryptionAlgorithm);
            _saveSyncLock = new AutoResetLock();
            
            CreateCacheController();
        }
开发者ID:Fedorm,项目名称:core-master,代码行数:46,代码来源:IsolatedStorageOfflineContext.cs


示例2: EncryptBytes

        public static byte[] EncryptBytes(SymmetricAlgorithm symAlg, byte[] inBlock)
        {
            ICryptoTransform xfrm = symAlg.CreateEncryptor();
            byte[] outBlock = xfrm.TransformFinalBlock(inBlock, 0, inBlock.Length);

            return outBlock;
        }
开发者ID:TheNaked,项目名称:Firewind,代码行数:7,代码来源:Encryption.cs


示例3: Decrypt

 private static string Decrypt(byte[] cipher, string passPhrase, string salt, SymmetricAlgorithm algorithm)
 {
     var saltBytes = Encoding.UTF8.GetBytes(salt);
     algorithm.Padding = PaddingMode.None;
     using (algorithm)
     {
         using (var password = new Rfc2898DeriveBytes(passPhrase, saltBytes))
         {
             algorithm.Key = password.GetBytes(algorithm.KeySize / 8);
             algorithm.IV = password.GetBytes(algorithm.BlockSize / 8);
             using (var memStream = new MemoryStream(cipher))
             {
                 using (
                     var cryptoStream = new CryptoStream(memStream, algorithm.CreateDecryptor(),
                                                         CryptoStreamMode.Read))
                 {
                     using (var sr = new StreamReader(cryptoStream))
                     {
                         return sr.ReadToEnd();
                     }
                 }
             }
         }
     }
 }
开发者ID:gilles1977,项目名称:epayment-integration,代码行数:25,代码来源:CryptoUtils.cs


示例4: SymCryptography

        public SymCryptography(string serviceProviderName)
        {
            // Select symmetric algorithm
            switch (serviceProviderName.ToLower())
            {
                case "rijndael":
                    serviceProviderName = "Rijndael";
                    _algorithm = ServiceProviderEnum.Rijndael;
                    break;
                case "rc2":
                    serviceProviderName = "RC2";
                    _algorithm = ServiceProviderEnum.RC2;
                    break;
                case "des":
                    serviceProviderName = "DES";
                    _algorithm = ServiceProviderEnum.DES;
                    break;
                case "tripledes":
                    serviceProviderName = "TripleDES";
                    _algorithm = ServiceProviderEnum.TripleDES;
                    break;
            }

            // Set symmetric algorithm
            _cryptoService = (SymmetricAlgorithm)CryptoConfig.CreateFromName(serviceProviderName);
            _cryptoService.Mode = CipherMode.CBC;
        }
开发者ID:rdvanbuuren,项目名称:SecureSettingsManager,代码行数:27,代码来源:SymCryptography.cs


示例5: CipherTextStealingMode

        /// <summary>
        /// Initialize CipherTextStealingMode with a specific symmetric algorithm
        /// </summary>
        /// <param name="symmetricAlgorithm">The symmetric algorithm</param>
        public CipherTextStealingMode(SymmetricAlgorithm symmetricAlgorithm)
        {
            // in CTS Mode there is no padding
            symmetricAlgorithm.Padding = PaddingMode.None;

            // set the symmetric algorithm's mode to ECB
            // (for single block encryption and decryption)
            symmetricAlgorithm.Mode = CipherMode.ECB;

            // get the symmetric algorithm's block size in bytes
            blockSize = symmetricAlgorithm.BlockSize / 8;
            if (blockSize != symmetricAlgorithm.IV.Length)
            {
                throw new ArgumentException(
                    "The IV size should equal to the block size.");
            }

            // initialize local IV
            iv = symmetricAlgorithm.IV;

            // initialize cipher state using the symmetric algorithms's IV
            cipherState = new byte[blockSize];
            symmetricAlgorithm.IV.CopyTo(cipherState, 0);

            // create encryptor and decryptor
            encryptor = symmetricAlgorithm.CreateEncryptor();
            decryptor = symmetricAlgorithm.CreateDecryptor();
        }
开发者ID:LiuXiaotian,项目名称:WindowsProtocolTestSuites,代码行数:32,代码来源:CipherTextStealingMode.cs


示例6: EncryptionWrapper

        public EncryptionWrapper(string algorithmName)
        {
            if (string.IsNullOrEmpty(algorithmName))
                throw new ArgumentNullException("algorithmName");

            algorithm = SymmetricAlgorithm.Create(algorithmName);
        }
开发者ID:scopely,项目名称:aws-sdk-net,代码行数:7,代码来源:EncryptionWrapper.cs


示例7: Crypter

        public Crypter(SymmetricAlgorithm symmetricAlg)
        {
            if (symmetricAlg == null)
            throw new ArgumentNullException();

              algorithm = symmetricAlg;
        }
开发者ID:Nirklav,项目名称:TCPChat,代码行数:7,代码来源:Crypter.cs


示例8: NetCryptoProviderBase

		public NetCryptoProviderBase(NetPeer peer, SymmetricAlgorithm algo)
			: base(peer)
		{
			m_algorithm = algo;
			m_algorithm.GenerateKey();
			m_algorithm.GenerateIV();
		}
开发者ID:KennethYap,项目名称:MonoGame,代码行数:7,代码来源:NetCryptoProviderBase.cs


示例9: CryptoTransformBase

        public CryptoTransformBase(SymmetricAlgorithm algo, bool encryption, byte[] rgbKey, byte[] rgbIV)
        {
            if (rgbKey == null)
                throw new CryptographicException("Invalid (null) key");

            BlockSizeByte = (algo.BlockSize >> 3);

            if (rgbIV == null)
            {
                iv = new byte[BlockSizeByte];
                this.Random(iv, 0, BlockSizeByte);
            }
            else
            {
                // compare the IV length with the "currently selected" block size and *ignore* IV that are too big
                if (rgbIV.Length < BlockSizeByte)
                {
                    string msg = Locale.GetText("IV is too small ({0} bytes), it should be {1} bytes long.",
                        rgbIV.Length, BlockSizeByte);
                    throw new CryptographicException(msg);
                }
                iv = (byte[])rgbIV.Clone();
            }

            encrypt = encryption;
            padding = algo.Padding;

            // transform buffer
            workBuff = new byte[BlockSizeByte];
        }
开发者ID:symform,项目名称:crimson,代码行数:30,代码来源:CryptoTransformBase.cs


示例10: Decrypt

        /// <summary>
        /// 解密数据.
        /// </summary>
        /// <param name="Doc"></param>
        /// <param name="Alg"></param>
        public static void Decrypt(XmlDocument Doc, SymmetricAlgorithm Alg)
        {
            // Check the arguments.
            if (Doc == null)
                throw new ArgumentNullException("Doc");
            if (Alg == null)
                throw new ArgumentNullException("Alg");

            // Find the EncryptedData element in the XmlDocument.
            XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement;

            // If the EncryptedData element was not found, throw an exception.
            if (encryptedElement == null)
            {
                throw new XmlException("The EncryptedData element was not found.");
            }

            // Create an EncryptedData object and populate it.
            EncryptedData edElement = new EncryptedData();
            edElement.LoadXml(encryptedElement);

            // Create a new EncryptedXml object.
            EncryptedXml exml = new EncryptedXml();

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

            // Replace the encryptedData element with the plaintext XML element.
            exml.ReplaceData(encryptedElement, rgbOutput);
        }
开发者ID:mahuidong,项目名称:my-csharp-sample,代码行数:35,代码来源:Program.cs


示例11: DecryptBytes

        private static byte[] DecryptBytes(SymmetricAlgorithm symAlg, byte[] inBytes)
        {
            ICryptoTransform xfrm = symAlg.CreateDecryptor();
            byte[] outBlock = xfrm.TransformFinalBlock(inBytes, 0, inBytes.Length);

            return outBlock;
        }
开发者ID:TheNaked,项目名称:Firewind,代码行数:7,代码来源:Program.cs


示例12: DeCrypt

        /// <summary>
        /// 通过制定的算法模式来加密一个字符串(不支持中文)
        /// </summary>
        /// <param name="Algorithm">解密的算法</param>
        /// <param name="ValueToDeCrypt">将要被解密的值</param>
        private static String DeCrypt(SymmetricAlgorithm Algorithm, String ValueToDeCrypt)
        {
            // Put the input string into the byte array.
            Byte[] InputByteArray = new Byte[ValueToDeCrypt.Length / 2];

            for (Int32 i = 0; i < ValueToDeCrypt.Length / 2; i++)
            {
                Int32 Value = (Convert.ToInt32(ValueToDeCrypt.Substring(i * 2, 2), 16));
                InputByteArray[i] = (Byte)Value;
            }

            // Create the crypto objects.
            String EncryptionKey = WhfEncryption.EncryptionKey;
            // Create the key.
            Byte[] Key = ASCIIEncoding.ASCII.GetBytes(EncryptionKey);
            Algorithm.Key = (Byte[])WhfEncryption.ReDim(Key, Algorithm.Key.Length);
            Algorithm.IV = (Byte[])WhfEncryption.ReDim(Key, Algorithm.IV.Length);

            MemoryStream MemStream = new MemoryStream();
            CryptoStream CrypStream = new CryptoStream(MemStream, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);

            // Flush the data through the crypto stream into the memory stream.
            CrypStream.Write(InputByteArray, 0, InputByteArray.Length);
            CrypStream.FlushFinalBlock();

            // Get the decrypted data back from the memory stream.
            StringBuilder StringBuilder = new StringBuilder();

            for (Int32 i = 0; i < MemStream.ToArray().Length; i++)
            {
                StringBuilder.Append((Char)MemStream.ToArray()[i]);
            }

            return StringBuilder.ToString();
        }
开发者ID:kevin-h-wang,项目名称:tuopu,代码行数:40,代码来源:WhfEncryption.cs


示例13: SymmetricDecrpyt

        /// <summary>
        /// Symmetrics decrpyt.
        /// </summary>
        /// <param name="str">The STR to decrpyt.</param>
        /// <param name="mobjCryptoService">A concrete symmetric algorithm.</param>
        /// <param name="key">The key.</param>
        /// <returns>The decrpyted str.</returns>
        public string SymmetricDecrpyt(string str, SymmetricAlgorithm mobjCryptoService, string key)
        {
            Check.Require(str != null, "str could not be null!");

            byte[] bytIn = Convert.FromBase64String(str);
            return UTF8Encoding.Unicode.GetString(SymmetricDecrpyt(bytIn, mobjCryptoService, key));
        }
开发者ID:Oman,项目名称:Maleos,代码行数:14,代码来源:CryptographyManager.cs


示例14: ConfigurarAlgoritmo

 private static void ConfigurarAlgoritmo(SymmetricAlgorithm algoritmo)
 {
     algoritmo.KeySize = 256;
     algoritmo.BlockSize = 128;
     algoritmo.Mode = CipherMode.CBC;
     algoritmo.Padding = PaddingMode.PKCS7;
 }
开发者ID:SebastianGerard,项目名称:AgromarketBolivia,代码行数:7,代码来源:Encriptar.cs


示例15: DecryptXmlDocument

        private static XmlDocument DecryptXmlDocument(XmlDocument encryptedXmlDocument, SymmetricAlgorithm sharedKey)
        {
            // Создание объекта для дешифрации XML
            var encryptedXml = new GostEncryptedXml(encryptedXmlDocument);

            var nsManager = new XmlNamespaceManager(encryptedXmlDocument.NameTable);
            nsManager.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);

            // Поиск всех зашифрованных XML-элементов
            var encryptedDataList = encryptedXmlDocument.SelectNodes("//enc:EncryptedData", nsManager);

            if (encryptedDataList != null)
            {
                foreach (XmlElement encryptedData in encryptedDataList)
                {
                    // Загрузка элемента EncryptedData
                    var elementEncryptedData = new EncryptedData();
                    elementEncryptedData.LoadXml(encryptedData);

                    // Расшифровка элемента EncryptedData
                    var decryptedData = encryptedXml.DecryptData(elementEncryptedData, sharedKey);

                    // Замена элемента EncryptedData его расшифрованным представлением
                    encryptedXml.ReplaceData(encryptedData, decryptedData);
                }
            }

            return encryptedXmlDocument;
        }
开发者ID:kapitanov,项目名称:GostCryptography,代码行数:29,代码来源:EncryptedXmlSharedKeyTest.cs


示例16: Encrypt

        public static byte[] Encrypt(string strText, SymmetricAlgorithm key)
        {
            // Create a memory stream.
            MemoryStream ms = new MemoryStream();

            // Create a CryptoStream using the memory stream and the
            // CSP(cryptoserviceprovider) DES key.
            CryptoStream crypstream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);

            // Create a StreamWriter to write a string to the stream.
            StreamWriter sw = new StreamWriter(crypstream);

            // Write the strText to the stream.
            sw.WriteLine(strText);

            // Close the StreamWriter and CryptoStream.
            sw.Close();
            crypstream.Close();

            // Get an array of bytes that represents the memory stream.
            byte[] buffer = ms.ToArray();

            // Close the memory stream.
            ms.Close();

            // Return the encrypted byte array.
            return buffer;
        }
开发者ID:ctsxamarintraining,项目名称:cts451785,代码行数:28,代码来源:SymmetricKeyEncryption.cs


示例17: Encrypt

 public void Encrypt( SymmetricAlgorithm algorithm, byte[] buffer, int offset, int length )
 {
     byte[] iv;
     byte[] cipherText;
     GenerateIVAndEncrypt( algorithm, buffer, offset, length, out iv, out cipherText );
     CipherData.SetCipherValueFragments( iv, cipherText );
 }
开发者ID:krytht,项目名称:DotNetReferenceSource,代码行数:7,代码来源:EncryptedDataElement.cs


示例18: StringEncryption

 /// <summary>
 /// Initializes a new StringEncryption instance.
 /// </summary>
 /// <param name="bulkCipher">The bulk cipher algorithm to use.</param>
 /// <param name="hash">The hash algorithm to use.</param>
 /// <exception cref="ArgumentNullException">One of the parameters is a null reference.</exception>
 public StringEncryption(SymmetricAlgorithm bulkCipher, HashAlgorithm hash) {
     if (bulkCipher == null)
         throw new ArgumentNullException("bulkCipher", ResourceController.GetString("Error_ParamNull"));
     if (hash == null)
         throw new ArgumentNullException("hash", ResourceController.GetString("Error_ParamNull"));
     Init(bulkCipher, hash);
 }
开发者ID:xxjeng,项目名称:nuxleus,代码行数:13,代码来源:StringEncryption.cs


示例19: ExtractIVAndDecrypt

        static byte[] ExtractIVAndDecrypt( SymmetricAlgorithm algorithm, byte[] cipherText, int offset, int count )
        {
            byte[] iv = new byte[algorithm.BlockSize / 8];

            //
            // Make sure cipherText has enough bytes after the offset, for Buffer.BlockCopy to copy.
            //
            if ( cipherText.Length - offset < iv.Length )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException( SR.GetString( SR.ID6019, cipherText.Length - offset, iv.Length ) ) );
            }

            Buffer.BlockCopy( cipherText, offset, iv, 0, iv.Length );

            algorithm.Padding = PaddingMode.ISO10126;
            algorithm.Mode = CipherMode.CBC;

            ICryptoTransform decrTransform = null;
            byte[] plainText = null;

            try
            {
                decrTransform = algorithm.CreateDecryptor( algorithm.Key, iv );
                plainText = decrTransform.TransformFinalBlock( cipherText, offset + iv.Length, count - iv.Length );
            }
            finally
            {
                if ( decrTransform != null )
                {
                    decrTransform.Dispose();
                }
            }

            return plainText;
        }
开发者ID:krytht,项目名称:DotNetReferenceSource,代码行数:35,代码来源:EncryptedDataElement.cs


示例20: Desencriptar

 public static byte[] Desencriptar(byte[] mensajeEncriptado,
     SymmetricAlgorithm algoritmo)
 {
     int numeroBytesDesencriptados = 0;
     // La clase SymmetricAlgorithm delega el proceso de desencriptación de datos
     // Una instancia de ICryptoTransform transforma texto plano en texto cifrado o vice versa.
     // Las siguiente sentencia demuestra como crear transformaciones usando CreateDecryptor.
     byte[] mensajeDesencriptado = new
     byte[mensajeEncriptado.Length];
     // Crear una ICryptoTransform que puede ser usada para desencriptar datos
     ICryptoTransform desencriptador =
         algoritmo.CreateDecryptor();
     // Procedemos a descifrar el mensaje
     MemoryStream memoryStream = new
     MemoryStream(mensajeEncriptado);
     // Creamos el CryptoStream
     CryptoStream cryptoStream = new CryptoStream(memoryStream,
         desencriptador, CryptoStreamMode.Read);
     // Decrypting data and get the count of plain text bytes.
     numeroBytesDesencriptados = cryptoStream.Read(mensajeDesencriptado, 0, mensajeDesencriptado.Length);
     // Liberamos recursos.
     memoryStream.Close();
     cryptoStream.Close();
     return mensajeDesencriptado;
 }
开发者ID:sancas,项目名称:ProgramacionIII,代码行数:25,代码来源:Program.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Cryptography.TripleDESCryptoServiceProvider类代码示例发布时间:2022-05-26
下一篇:
C# Cryptography.SafeProvHandle类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap