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


C# AesCryptoServiceProvider.GenerateKey方法代码示例

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


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

示例1: TestKeyGeneration

    private static bool TestKeyGeneration()
    {
        try
        {
            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {

                // Try creating the other sized keys
                aes.KeySize = 128;
                if (aes.Key.Size != 128)
                    return false;

                // Make sure consecutive reads don't change the key
                aes.GenerateKey();
                byte[] read1 = aes.Key.ExportKey(true);
                byte[] read2 = aes.Key.ExportKey(true);

                if (!CompareBytes(read1, read2))
                    return false;
            }

            return true;
        }
        catch
        {
            return false;
        }
    }
开发者ID:koson,项目名称:.NETMF_for_LPC17xx,代码行数:28,代码来源:KeySizeTests.cs

示例2: GenerateEncryptionKey

 /// <summary>
 /// Generates an encryption key.
 /// </summary>
 /// <returns>byte[] encryption key. Store it some place
 /// safe.</returns>
 static public byte[] GenerateEncryptionKey()
 {
     //Generate a Key.
     var aesProvider = new AesCryptoServiceProvider();
     aesProvider.GenerateKey();
     return aesProvider.Key;
 }
开发者ID:peelybird,项目名称:Beetree.AESCrypto,代码行数:12,代码来源:SimpleAES.cs

示例3: 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

示例4: SessionTest_CloseWithCreateKeyObjects_internal

        bool SessionTest_CloseWithCreateKeyObjects_internal(string svcProvider)
        {
            bool res = true;

            CryptoKey key;

            using (Session sess = new Session(svcProvider, MechanismType.AES_CBC))
            {
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider(sess);

                aes.GenerateKey();

                key = aes.Key;

                SymmetricTestHelper.Test_EncryptUpdate(aes);
            }

            try
            {
                using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider(svcProvider))
                {
                    aes.Key = key;

                    SymmetricTestHelper.Test_EncryptUpdate(aes);
                }

                res = false;
            }
            catch (Exception)
            {
            }

            return res;
        }
开发者ID:koson,项目名称:.NETMF_for_LPC17xx,代码行数:34,代码来源:SessionTests.cs

示例5: 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

示例6: 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

示例7: GenerateDecryptionKey

 public string GenerateDecryptionKey()
 {
     using (var decr = new AesCryptoServiceProvider())
     {
         decr.GenerateKey();
         return BinaryToHex(decr.Key);
     }
 }
开发者ID:mdavid626,项目名称:triton,代码行数:8,代码来源:MachineKeyGenerator.cs

示例8: AesTest

 public void AesTest()
 {
     var symmetricAlgorithm = new AesCryptoServiceProvider();
     symmetricAlgorithm.GenerateKey();
     var key = symmetricAlgorithm.Key;
     Console.WriteLine(symmetricAlgorithm.KeySize);
     Console.WriteLine(symmetricAlgorithm.BlockSize);
     Console.WriteLine(Convert.ToBase64String(key));
 }
开发者ID:shestakov,项目名称:NeuroPrognosis,代码行数:9,代码来源:AuthenticationTokenCryptography_Test.cs

示例9: 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

示例10: createSerializedKey

		// Create a serialized object of type Key.
		// The key data is created with .NET: AesCryptoServiceProvider.GenerateKey.
		public static string createSerializedKey()
		{
			using (var aes = new AesCryptoServiceProvider())
			{

				aes.GenerateKey();
				/* osu change: uncomment
				Log.I("AESKeySize: {0}".format(aes.KeySize));
				*/
					
				return makeKey(aes).serialize();
			}
		}
开发者ID:sharedsafe,项目名称:SharedSafe.Encoding,代码行数:15,代码来源:Encryption.cs

示例11: 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

示例12: TestSymmetricKeyProvider

        public TestSymmetricKeyProvider()
        {
            byte[] key;
            byte[] iv;

            using (var provider = new AesCryptoServiceProvider())
            {
                provider.GenerateIV();
                provider.GenerateKey();

                key = provider.Key;
                iv = provider.IV;

                provider.Clear();
            }

            _key = new TestSymmetricKey(key, iv);
        }
开发者ID:nicklv,项目名称:MassTransit,代码行数:18,代码来源:TestSymmetricKeyProvider.cs

示例13: Main

        static void Main()
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.GenerateKey();
            aes.GenerateIV();

            //Tworzenie CryptoTransform
            ICryptoTransform En = aes.CreateEncryptor();
            ICryptoTransform De = aes.CreateDecryptor();

            //Tworzenie potrzebnych zmiennych
            byte[] before = Encoding.UTF8.GetBytes("AES");
            byte[] after;
            byte[] end = new byte[1024];
            string result;

            //szyfrowanie
            using (MemoryStream mem = new MemoryStream())
            {
                using (CryptoStream crypt = new CryptoStream(mem, En, CryptoStreamMode.Write))
                {
                    crypt.Write(before, 0, before.Length);
                }
                after = mem.ToArray();
            }

            //deszyfracja
            using (MemoryStream mem = new MemoryStream(after))
            {
                int i;
                using (CryptoStream crypt = new CryptoStream(mem, De, CryptoStreamMode.Read))
                {
                    i = crypt.Read(end, 0, end.Length);
                }
                result = Encoding.UTF8.GetString(end, 0, i);
            }

            //wypisanie na ekran informacji.
            Console.WriteLine("Wiadomość: {0}", Encoding.UTF8.GetString(before));
            Console.WriteLine("Zaszyfrowana wiadomość: {0}", Encoding.UTF8.GetString(after));
            Console.WriteLine("Odszyfrowana wiadomość: {0}", result);
            Console.ReadKey();
        }
开发者ID:CodersCommunity,项目名称:csharp-materialy,代码行数:43,代码来源:AES_szyfracja_deszyfracja.cs

示例14: HandShake

        /// <summary>
        ///     Generate a random AES pass key and securely send it to the server
        ///     <returns>True if successfully authenticated</returns>
        /// </summary>
        public static bool HandShake()
        {
            try
            {
                var keyPath = string.Format("{0}tmp\\public.cer", AppDomain.CurrentDomain.BaseDirectory);
                Communication.DownloadFile("/management/other/ssl/srvpublic.crt", keyPath);

                var aes = new AesCryptoServiceProvider();
                aes.GenerateKey();
                Passkey = aes.Key;
                var token = GetSecurityToken("token.dat");

                var certificate = new X509Certificate2(keyPath);

                if (!Data.RSA.IsFromCA(Data.RSA.GetCACertificate(), certificate))
                    throw new Exception("Certificate is not from FOG CA");

                Log.Entry(LogName, "Cert OK");

                var enKey = Data.Transform.ByteArrayToHexString(Data.RSA.Encrypt(certificate, Passkey));
                var enToken = Data.Transform.ByteArrayToHexString(Data.RSA.Encrypt(certificate, token));

                var response = Communication.Post("/management/index.php?sub=authorize", string.Format("sym_key={0}&token={1}&mac={2}", enKey, enToken, Configuration.MACAddresses()));

                if (!response.Error)
                {
                    Log.Entry(LogName, "Authenticated");
                    SetSecurityToken("token.dat", Data.Transform.HexStringToByteArray(response.GetField("#token")));
                    return true;
                }

                if (response.ReturnCode.Equals("#!ih"))
                    Communication.Contact(string.Format("/service/register.php?hostname={0}", Dns.GetHostName()), true);

            }
            catch (Exception ex)
            {
                Log.Error(LogName, "Could not authenticate");
                Log.Error(LogName, ex);
            }

            return false;
        }
开发者ID:uw-it-cte,项目名称:fog-client,代码行数:47,代码来源:Authentication.cs

示例15: Encrypt_Decrypt_RoundTrips

        public void Encrypt_Decrypt_RoundTrips()
        {
            // Arrange
            var aes = new AesCryptoServiceProvider();
            aes.GenerateKey();

            var serviceCollection = new ServiceCollection();
            var mockInternalEncryptor = new Mock<IInternalCertificateXmlEncryptor>();
            mockInternalEncryptor.Setup(o => o.PerformEncryption(It.IsAny<EncryptedXml>(), It.IsAny<XmlElement>()))
                .Returns<EncryptedXml, XmlElement>((encryptedXml, element) =>
                {
                    encryptedXml.AddKeyNameMapping("theKey", aes); // use symmetric encryption
                    return encryptedXml.Encrypt(element, "theKey");
                });
            serviceCollection.AddInstance<IInternalCertificateXmlEncryptor>(mockInternalEncryptor.Object);

            var mockInternalDecryptor = new Mock<IInternalEncryptedXmlDecryptor>();
            mockInternalDecryptor.Setup(o => o.PerformPreDecryptionSetup(It.IsAny<EncryptedXml>()))
                .Callback<EncryptedXml>(encryptedXml =>
                {
                    encryptedXml.AddKeyNameMapping("theKey", aes); // use symmetric encryption
                });
            serviceCollection.AddInstance<IInternalEncryptedXmlDecryptor>(mockInternalDecryptor.Object);

            var services = serviceCollection.BuildServiceProvider();
            var encryptor = new CertificateXmlEncryptor(services);
            var decryptor = new EncryptedXmlDecryptor(services);

            var originalXml = XElement.Parse(@"<mySecret value='265ee4ea-ade2-43b1-b706-09b259e58b6b' />");

            // Act & assert - run through encryptor and make sure we get back <EncryptedData> element
            var encryptedXmlInfo = encryptor.Encrypt(originalXml);
            Assert.Equal(typeof(EncryptedXmlDecryptor), encryptedXmlInfo.DecryptorType);
            Assert.Equal(XName.Get("EncryptedData", "http://www.w3.org/2001/04/xmlenc#"), encryptedXmlInfo.EncryptedElement.Name);
            Assert.Equal("http://www.w3.org/2001/04/xmlenc#Element", (string)encryptedXmlInfo.EncryptedElement.Attribute("Type"));
            Assert.DoesNotContain("265ee4ea-ade2-43b1-b706-09b259e58b6b", encryptedXmlInfo.EncryptedElement.ToString(), StringComparison.OrdinalIgnoreCase);

            // Act & assert - run through decryptor and make sure we get back the original value
            var roundTrippedElement = decryptor.Decrypt(encryptedXmlInfo.EncryptedElement);
            XmlAssert.Equal(originalXml, roundTrippedElement);
        }
开发者ID:hishamco,项目名称:DataProtection,代码行数:41,代码来源:CertificateXmlEncryptionTests.cs


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