當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。