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


C# AesCryptoServiceProvider.GenerateIV方法代码示例

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


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

示例1: Encrypt

        /// <summary>
        /// AES Encryption
        /// </summary>
        public static string Encrypt(string clearText)
        {
            if (clearText == null) return null;
            // AesCryptoServiceProvider
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize = 128;

            aes.GenerateIV();
            aes.Key = Encoding.UTF8.GetBytes(AesKey);
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            // Convert string to byte array
            byte[] src = Encoding.Unicode.GetBytes(clearText);

            // encryption
            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                // Convert byte array to Base64 strings
                return Convert.ToBase64String(aes.IV) + Convert.ToBase64String(dest);
            }
        }
开发者ID:RobertMandache,项目名称:StorageHub,代码行数:28,代码来源:Encryption.cs

示例2: Encription

        public byte[] Encription(string message, byte[] bobPubKeyBlob)
        {
            byte[] rawData = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;

            using (var aliceAlgorithm = new ECDiffieHellmanCng(privKey))
            using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob,
                  CngKeyBlobFormat.EccPublicBlob))
            {
                byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
                using (var aes = new AesCryptoServiceProvider())
                {
                    aes.Key = symmKey;
                    aes.GenerateIV();
                    using (ICryptoTransform encryptor = aes.CreateEncryptor())
                    using (MemoryStream ms = new MemoryStream())
                    {
                        // create CryptoStream and encrypt data to send
                        var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);

                        // write initialization vector not encrypted
                        ms.Write(aes.IV, 0, aes.IV.Length);
                        cs.Write(rawData, 0, rawData.Length);
                        cs.Close();
                        encryptedData = ms.ToArray();
                    }
                    aes.Clear();
                }
            }
            return encryptedData;
        }
开发者ID:mohankumarcm,项目名称:sse554-project3,代码行数:31,代码来源:EncriptionDecription.cs

示例3: EncryptByBlocks

 protected override string EncryptByBlocks(byte[] key,
     List<byte> plainText)
 {
     var cipherText = new StringBuilder();
     if (plainText.Count % BlockSize == 0)
     {
         AddDummyBlock(plainText);
     }
     using (var aes = new AesCryptoServiceProvider())
     {
         aes.BlockSize = BlockSize * 8;
         aes.KeySize = KeySize * 8;
         aes.Padding = PaddingMode.None;
         aes.Key = key;
         aes.GenerateIV();
         cipherText.Append(BytesToHexString(aes.IV));
         using (var encr = aes.CreateEncryptor())
         {
             while (plainText.Count != 0)
             {
                 var block = DetachBlock(plainText);
                 if (block.Length < BlockSize)
                 {
                     block = CompleteBlock(block);
                 }
                 var encrypted = new byte[BlockSize];
                 encr.TransformBlock(block, 0, BlockSize, encrypted, 0);
                 cipherText.Append(BytesToHexString(encrypted));
                 aes.IV = encrypted;
             }
         }
     }
     return cipherText.ToString();
 }
开发者ID:yurkova,项目名称:cryptography_I,代码行数:34,代码来源:CbcAes.cs

示例4: Encrypt

        public void Encrypt(string filename)
        {
            FileStream fsInput = new FileStream(filename, FileMode.Open, FileAccess.Read);
            FileStream fsOutput = new FileStream(filename + ".crypt", FileMode.Create, FileAccess.Write);
            AesCryptoServiceProvider Aes = new AesCryptoServiceProvider();

            Aes.KeySize = 128;
            Aes.GenerateIV();
            Aes.GenerateKey();

            byte[] output = _algorithm_asym.Encrypt(Aes.Key, false);
            fsOutput.Write(output, 0, 256);
            output = _algorithm_asym.Encrypt(Aes.IV, false);
            fsOutput.Write(output, 0, 256);

            ICryptoTransform encrypt = Aes.CreateEncryptor();
            CryptoStream cryptostream = new CryptoStream(fsOutput, encrypt, CryptoStreamMode.Write);

            byte[] bytearrayinput = new byte[fsInput.Length - 1];
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);

            fsInput.Close();
            fsOutput.Close();
        }
开发者ID:Jupotter,项目名称:virologie,代码行数:25,代码来源:FileEncryption.cs

示例5: GenerateEncryptionVector

 /// <summary>
 /// Generates a unique encryption vector
 /// </summary>
 /// <returns>byte[] vector value</returns>
 static public byte[] GenerateEncryptionVector()
 {
     //Generate a Vector
     var aesProvider = new AesCryptoServiceProvider();
     aesProvider.GenerateIV();
     return aesProvider.IV;
 }
开发者ID:peelybird,项目名称:Beetree.AESCrypto,代码行数:11,代码来源:SimpleAES.cs

示例6: AliceSendData

        private static byte[] AliceSendData(string msg)
        {
            Console.WriteLine(string.Format("Alice Send Msg: {0}", msg));
            byte[] rawdata = Encoding.UTF8.GetBytes(msg);
            byte[] encryptedData = null;
            using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey))
            using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
            {
                byte[] symmkey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);

                Console.WriteLine(string.Format("Alice Create this symmtric key with {0}", Convert.ToBase64String(symmkey)));

                var aes = new AesCryptoServiceProvider();
                aes.Key = symmkey;
                aes.GenerateIV();
                using (ICryptoTransform encryptor = aes.CreateEncryptor())
                using (MemoryStream ms = new MemoryStream())
                {
                    var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
                    ms.Write(aes.IV, 0, aes.IV.Length);
                    cs.Write(rawdata, 0, rawdata.Length);
                    cs.Close();
                    encryptedData = ms.ToArray();
                }
                aes.Clear();
            }

            Console.WriteLine(Convert.ToBase64String(encryptedData));
            return encryptedData;
        }
开发者ID:niujiale,项目名称:SecurityTransportation,代码行数:30,代码来源:Program.cs

示例7: OnGenerate

        private void OnGenerate(object sender, EventArgs e)
        {
            // Create the AES provider.
            using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
            {
                // Generate the IV.
                aesProvider.GenerateIV();
                // Generate the key.
                aesProvider.GenerateKey();

                StringBuilder builder = new StringBuilder();

                foreach (byte b in aesProvider.IV)
                {
                    builder.AppendFormat("0x{0:X2}, ", b);
                }

                this.textBoxIv.Text = builder.ToString();

                builder.Clear();

                foreach(byte b in aesProvider.Key)
                {
                    builder.AppendFormat("0x{0:X2}, ", b);
                }

                this.textBoxKey.Text = builder.ToString();
            }
        }
开发者ID:alexbikfalvi,项目名称:DotNetApi,代码行数:29,代码来源:FormMain.cs

示例8: Encrypt

        public static byte[] Encrypt(byte[] input, byte[] key)
        {
            if (key == null || key.Length == 0) throw new Exception("Key can not be empty.");

            using (var md5 = new MD5CryptoServiceProvider())
            {
                key = md5.ComputeHash(key);
            }

            byte[] data = input, encdata = new byte[0];

            try
            {
                using (var ms = new MemoryStream())
                {
                    using (var aesProvider = new AesCryptoServiceProvider() { Key = key })
                    {
                        aesProvider.GenerateIV();

                        using (var cs = new CryptoStream(ms, aesProvider.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            ms.Write(aesProvider.IV, 0, aesProvider.IV.Length); // write first 16 bytes IV, followed by encrypted message
                            cs.Write(data, 0, data.Length);
                        }
                    }

                    encdata = ms.ToArray();
                }
            }
            catch
            {
            }
            return encdata;
        }
开发者ID:yashodhank,项目名称:QuasarRAT,代码行数:34,代码来源:AES.cs

示例9: AliceSendsData

        private async static Task<byte[]> AliceSendsData(string message)
        {
            Console.WriteLine("Alice send message {0}", message);
            byte[] rawData = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;

            using(var aliceAlgo = new ECDiffieHellmanCng(aliceKey))
            {
                using(CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.GenericPublicBlob))
                {
                    byte[] symmKey = aliceAlgo.DeriveKeyMaterial(bobPubKey);
                    Console.WriteLine("Alice create this symm key with Bobs public key information : {0}", Convert.ToBase64String(symmKey));
                    using(var aes = new AesCryptoServiceProvider())
                    {
                        aes.Key = symmKey;
                        aes.GenerateIV();
                        using(ICryptoTransform encryptor = aes.CreateEncryptor())
                        {
                            using(MemoryStream ms = new MemoryStream())
                            {
                                var cs = new CryptoStream(ms, encryptor,CryptoStreamMode.Write);
                                await ms.WriteAsync(aes.IV, 0, aes.IV.Length);
                                cs.Write(rawData, 0, rawData.Length);
                                cs.Close();
                                encryptedData = ms.ToArray();
                            }
                        }
                        aes.Clear();
                    }
                }
            }
            Console.WriteLine("Alice message is encrypted : {0}", Convert.ToBase64String(encryptedData));
            return encryptedData;
        }
开发者ID:xxy1991,项目名称:cozy,代码行数:34,代码来源:ExchangeAndTransfer.cs

示例10: Application_Start

        protected void Application_Start()
        {
            //HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config")));
            GlobalConfig.Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            var container = new Container();
            SimpleInjectorInitializer.InitializeInjector(container);
            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

            GlobalConfig.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            GlobalConfig.GadgetTypes = new System.Collections.Concurrent.ConcurrentDictionary<string, Type>();

            LoadGadgets();

            var aesCsp = new AesCryptoServiceProvider();
            aesCsp.GenerateKey();
            aesCsp.GenerateIV();
            GlobalConfig.Encryptor = new SimpleAES(aesCsp.Key, aesCsp.IV);
        }
开发者ID:calexander3,项目名称:Damage,代码行数:27,代码来源:Global.asax.cs

示例11: generateAESKey

 public static AesCryptoServiceProvider generateAESKey()
 {
     AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
     aes.KeySize = 256;
     aes.GenerateKey();
     aes.GenerateIV();
     
     return aes;
 }
开发者ID:ernvalentino88,项目名称:pds_project,代码行数:9,代码来源:Security.cs

示例12: createRandomIV

		// Create an object of type IV from a given object of type Key.
		// Usage of AesCryptoServiceProvider:
		// - create it 
		// - set its key size according the the size of the input Key
		// - use GenerateIV()
		public static IV createRandomIV(Key key)
		{
			using (var aes = new AesCryptoServiceProvider())
			{
				aes.KeySize = key.Format.BitSize.signed();
				// this should not be required?
				// aes.Key = key.Data;

				aes.GenerateIV();
				return new IV(aes.IV);
			}
		}
开发者ID:sharedsafe,项目名称:SharedSafe.Encoding,代码行数:17,代码来源:Encryption.cs

示例13: AesEncrypt

        /// <summary>
        /// Encrypt data with AES algorithm
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static byte[] AesEncrypt(byte[] data, out byte[] key, out byte[] iv)
        {
            if (data == null)
                throw new ArgumentNullException("No data to encrypt.");

            using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
            {
                provider.GenerateKey();
                provider.GenerateIV();
                key = provider.Key;
                iv = provider.IV;
                return provider.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
            }
        }
开发者ID:barbarossia,项目名称:DIS,代码行数:21,代码来源:EncryptionHelper.cs

示例14: getProvider

        private static AesCryptoServiceProvider getProvider(byte[] keyPhrase)
        {
            AesCryptoServiceProvider result = new AesCryptoServiceProvider();
            result.BlockSize = 128;
            result.KeySize = 128;
            result.Mode = CipherMode.CBC;
            result.Padding = PaddingMode.PKCS7;

            result.GenerateIV();
            result.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            byte[] key = getKey(keyPhrase, result);
            result.Key = key;
            // result.IV = RealKey;
            return result;
        }
开发者ID:allanckw,项目名称:GEMS-Web,代码行数:16,代码来源:Mobile_AES.cs

示例15: Encrypt

        public static byte[] Encrypt(byte[] input, byte[] password, ushort saltSize, int iterations)
        {
            var salt = CreateSalt(saltSize);

            using (var aes = new AesCryptoServiceProvider())
            {
                aes.BlockSize = 128;
                aes.KeySize = 256;
                using (var key = new Rfc2898DeriveBytes(password, salt, iterations))
                {
                    aes.Key = key.GetBytes(16);
                    aes.Mode = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;

                    aes.GenerateIV();

                    using (var memStream = new MemoryStream())
                    {
                        //While a byte would suffice, 
                        //we'll take the sure-thing and just use a ushort instead, this allows a key-length of 65535 tokens.
                        var bytes = new byte[sizeof(ushort)];
                        
                        fixed (void* b = bytes)
                            *((ushort*)b) = saltSize;
                        memStream.Write(bytes, 0, bytes.Length);

                        fixed (void* b = bytes)
                            *((ushort*)b) = (ushort)aes.IV.Length;
                        memStream.Write(bytes, 0, bytes.Length);

                        memStream.Write(salt, 0, salt.Length);
                        memStream.Write(aes.IV, 0, aes.IV.Length);

                        using (var encryptor = aes.CreateEncryptor())
                        using (var cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(input, 0, input.Length);
                            cryptoStream.FlushFinalBlock();

                            var encrypted = memStream.ToArray();
                            return encrypted;
                        }
                    }
                }
            }
        }
开发者ID:StevenThuriot,项目名称:Vault.Core,代码行数:46,代码来源:Security.cs


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