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


C# RNGCryptoServiceProvider.GetBytes方法代码示例

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


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

示例1: CreateReference

        public string CreateReference(int size)
        {
            const int byteSize = 0x100;
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            var allowedCharSet = new HashSet<char>(chars).ToArray();

            using (var cryptoProvider = new RNGCryptoServiceProvider())
            {
                var result = new StringBuilder();
                var buffer = new byte[128];

                while (result.Length < size)
                {
                    cryptoProvider.GetBytes(buffer);

                    for (var i = 0; i < buffer.Length && result.Length < size; ++i)
                    {
                        var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);

                        if (outOfRangeStart <= buffer[i])
                        {
                            continue;
                        }

                        result.Append(allowedCharSet[buffer[i] % allowedCharSet.Length]);
                    }
                }
                return result.ToString();
            }
        }
开发者ID:letmeproperty,项目名称:TransactionalSMS,代码行数:30,代码来源:CryptographicReferenceGenerator.cs

示例2: Test

        public string Test()
        {
            byte[] key = new byte[32];
            byte[] iv = new byte[8];
            byte[] data = new byte[BlockCount * 64];
            string ft = @"m\:ss\.ff";
            Stopwatch runTimer = new Stopwatch();

            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(key);
                rng.GetBytes(iv);
                rng.GetBytes(data);
            }

            runTimer.Start();

            if (this.Implementation == SalsaImplementations.Ver1)
            {
                for (int i = 0; i < Iterations; i++)
                    Salsa1Test(key, iv, data);
            }
            else
            {
                for (int i = 0; i < Iterations; i++)
                    Salsa2Test(key, iv, data);
            }

            runTimer.Stop();
            TimeSpan t1 = TimeSpan.FromMilliseconds(runTimer.Elapsed.TotalMilliseconds);

            return t1.ToString(ft);
        }
开发者ID:modulexcite,项目名称:CEX,代码行数:33,代码来源:SalsaSpeed.cs

示例3: ConsoleListener

        /// <summary>
        /// 
        /// </summary>
        public ConsoleListener()
        {
            using (var numberGen = new RNGCryptoServiceProvider())
            {
                var data = new byte[20];
                var data2 = new byte[20];
                numberGen.GetBytes(data);
                numberGen.GetBytes(data2);

                using(MD5 md5 = new MD5CryptoServiceProvider())
                {
                    string str = ServerSettings.Salt2 + Convert.ToBase64String(data) + Convert.ToBase64String(data2) + ServerSettings.Salt;
                    byte[] buffer = new byte[str.Length * 2];
                    Encoding.Unicode.GetEncoder().GetBytes(str.ToCharArray(), 0, str.Length, buffer, 0, true);
                    byte[] result = md5.ComputeHash(buffer);

                    StringBuilder sb = new StringBuilder();

                    for (int i = 0; i < result.Length; i++)
                        sb.Append(result[i].ToString("X2"));

                    this.XID = sb.ToString();
                }
            }
        }
开发者ID:headdetect,项目名称:MCForge6-Vanilla,代码行数:28,代码来源:ConsoleListener.cs

示例4: Test

        /// <summary>
        /// CBC mode speed comparisons between RijndaelManaged and RDX
        /// </summary>
        /// <param name="Iterations">Number of times to perform this test</param>
        /// <param name="BlockCount">Number of 16 byte blocks to encrypt</param>
        /// <returns>Elapsed milliseconds [string]</returns>
        public string Test()
        {
            byte[] key = new byte[32];
            byte[] iv = new byte[16];
            byte[] data = new byte[this.BlockCount * 16];
            string ft = @"m\:ss\.ff";
            Stopwatch runTimer = new Stopwatch();

            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(key);
                rng.GetBytes(iv);
                rng.GetBytes(data);
            }

            runTimer.Start();

            for (int i = 0; i < this.Iterations; i++)
                PerformTest(key, iv, data);

            runTimer.Stop();
            TimeSpan t1 = TimeSpan.FromMilliseconds(runTimer.Elapsed.TotalMilliseconds);

            return t1.ToString(ft);
        }
开发者ID:modulexcite,项目名称:CEX,代码行数:31,代码来源:AesSpeed.cs

示例5: GetRandomString

		public static string GetRandomString(int length)
		{
			//returns random string of length specified with characters including: 0-9, a-z, A-Z
			char[] ca = new char[length];
			byte[] random = new Byte[length];
			//RNGCryptoServiceProvider is an implementation of a random number generator.

			RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
			rng.GetBytes(random); // The array is now filled with cryptographically strong random bytes.

			for (int i = 0; i < length; i++)
			{
				bool found = false;
				int rand = (int)random[i];
				while (!found)
				{
					if (((rand >= 48) && (rand <= 57)) || ((rand >= 65) && (rand <= 90)) || ((rand >= 97) && (rand <= 122)))
					{
						found = true;
					}
					else
					{
						//get a new random int. 
						byte[] single = new byte[1];
						rng.GetBytes(single);
						rand = single[0];
					}
				}
				char ci = (char)rand;
				ca[i] = ci;
			}
			string s = new string(ca);
			return s;
		}
开发者ID:stevensrf1,项目名称:iws-snippets,代码行数:34,代码来源:Utility.cs

示例6: testRng

        bool testRng(Session session)
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(session);

            byte[] data1 = new byte[1024];
            byte[] data2 = new byte[1024];
            byte[] data3 = new byte[1024];

            rng.GetBytes(data1);
            rng.GetBytes(data2);
            rng.Dispose();

            rng = new RNGCryptoServiceProvider(session);

            rng.GetBytes(data3);
            rng.Dispose();

            int same = 0;
            for (int i = 0; i < data1.Length; i++)
            {
                if (data1[i] == data2[i] || data1[i] == data3[i] || data2[i] == data3[i]) same++;
            }

            return same < 32; // ~3% matching elements
        }
开发者ID:koson,项目名称:.NETMF_for_LPC17xx,代码行数:25,代码来源:RNGTest.cs

示例7: CompareBlocks

        private void CompareBlocks(int BlockSize)
        {
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                byte[] key = new byte[32];
                byte[] iv = new byte[BlockSize];
                byte[] data = new byte[1600];

                rng.GetBytes(key);
                rng.GetBytes(iv);
                rng.GetBytes(data);

                byte[] enc1 = EncryptRDX(key, iv, data);
                byte[] enc2 = EncryptManaged(key, iv, data);

                if (Compare.AreEqual(enc1, enc2) == false)
                    throw new Exception("Encrypted output is not equal!");

                byte[] dec1 = DecryptRDX(key, iv, data);
                byte[] dec2 = DecryptManaged(key, iv, data);

                if (Compare.AreEqual(dec2, dec1) == false)
                    throw new Exception("Decrypted output is not equal to input data!");
            }
        }
开发者ID:modulexcite,项目名称:CEX,代码行数:25,代码来源:RijndaelEquality.cs

示例8: Send

        public void Send(double mouseX,double mouseY)
        {
            cid = getCID();
                sid = getSID();
                var callerID = sid;
                Random rnd = new Random(DateTime.Now.Millisecond);
                RNGCryptoServiceProvider rngc = new RNGCryptoServiceProvider();

                byte[] bta = new byte[1];
                rngc.GetBytes(bta);
                int _signal = bta[0] % 25; //0~24
                if (_signal < 5)   //5/25垂直或水平座標線
                    signal = 0;
                if (_signal ==5||_signal==6)   //2/25聲納探測
                    signal = 1;
                if (_signal >6 && _signal<=10)   //4/25隨機數字+引線
                    signal = 2;
                if (_signal ==11)   //1/25 gooleTTS!!
                    signal = 3;
                if (_signal > 11&&_signal<=16)   //5/25 移動座標線
                    signal = 4;
                if (_signal > 16 &&_signal <= 19)   //3/25 虛線
                    signal = 5;
                if (_signal > 19 && _signal <= 21)   //2/25 資料傳送
                    signal = 6;
                if (_signal > 21 && _signal <= 24)   //3/25 Glich
                    signal = 7;

                bool b     =rnd.Next(2)==1?true:false;
                Color col = Color.FromArgb(rnd.Next(90), rnd.Next(90)+50, rnd.Next(90)+160);
                string rndColor = ColorTranslator.ToHtml(col);
                string[] usercolors = { "#6dffff", "#FFB6FF", "#FFFA64", "#7BFFB9", "#AA6BFF" };
                string userColor = usercolors[Math.Abs(sid.GetHashCode() % 5)];
               rngc.GetBytes(bta);
                double r1 = (double)bta[0] / 256.0;
                rngc.GetBytes(bta);
                double r2 = (double)bta[0] / 256.0;
                string words = "";
                if (signal == 3) //其他不需要
                {
                    for (int i = 0; i < (r1 * 4 + 2); i++)
                    {
                        rngc.GetBytes(bta);
                        int sRnd = (Int32)bta[0];
                        for (int j = 0; j < sRnd; j++)
                            rnd.Next();
                        words += Global.dictionary[rnd.Next(Global.dictionary.Count)] + " ";
                        if (words.Length > 30)
                            break;
                    }
                }
                if (signal == 7)
                    Clients.Caller.broadcast(mouseX, mouseY, signal, b, rndColor, r1, r2, words, callerID, userColor);

                else {
                Clients.All.broadcast(mouseX, mouseY, signal, b, rndColor, r1, r2, words, callerID, userColor);
                Clients.All.osc(new object[] { mouseX, mouseY, signal, b, rndColor, r1, r2, words, callerID, userColor });
                }
        }
开发者ID:hwdayan,项目名称:Closure,代码行数:59,代码来源:Closure.cs

示例9: MachineKeyConfig

		static MachineKeyConfig ()
		{
			autogenerated = new byte [64];
			RNGCryptoServiceProvider cp = new RNGCryptoServiceProvider ();
			cp.GetBytes (autogenerated);
			autogenerated_decrypt = new byte [64];
			cp.GetBytes (autogenerated_decrypt);
		}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:8,代码来源:MachineKeyConfig.cs

示例10: AES

 /// <summary>
 /// Generate a new key and IV.
 /// </summary>
 /// <param name="encoding"></param>
 public AES(Encoding encoding)
 {
     this.mode = new SicBlockCipher(new AesFastEngine());
     RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
     // Generate random key and IV
     rngCsp.GetBytes(key);
     rngCsp.GetBytes(iv);
     this.encoding = encoding;
 }
开发者ID:paralin,项目名称:MatrixServer,代码行数:13,代码来源:AES.cs

示例11: GeneratePassword

        /// <summary>
        /// Creates a pseudo-random password containing the number of character classes
        /// defined by complexity, where 2 = alpha, 3 = alpha+num, 4 = alpha+num+special.
        /// </summary>
        public static string GeneratePassword(int length, int complexity)
        {
            System.Security.Cryptography.RNGCryptoServiceProvider csp =
            new System.Security.Cryptography.RNGCryptoServiceProvider();
            // Define the possible character classes where complexity defines the number
            // of classes to include in the final output.
            char[][] classes =
            {
            @"abcdefghijklmnopqrstuvwxyz".ToCharArray(),
            @"ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(),
            @"0123456789".ToCharArray(),
            @" !""#$%&'()*+,./:;<>[email protected][\]^_{|}~".ToCharArray(),
            };

            complexity = Math.Max(1, Math.Min(classes.Length, complexity));
            if (length < complexity)
                throw new ArgumentOutOfRangeException("length");

            // Since we are taking a random number 0-255 and modulo that by the number of
            // characters, characters that appear earilier in this array will recieve a
            // heavier weight. To counter this we will then reorder the array randomly.
            // This should prevent any specific character class from recieving a priority
            // based on it's order.
            char[] allchars = classes.Take(complexity).SelectMany(c => c).ToArray();
            byte[] bytes = new byte[allchars.Length];
            csp.GetBytes(bytes);
            for (int i = 0; i < allchars.Length; i++)
            {
                char tmp = allchars[i];
                allchars[i] = allchars[bytes[i] % allchars.Length];
                allchars[bytes[i] % allchars.Length] = tmp;
            }

            // Create the random values to select the characters
            Array.Resize(ref bytes, length);
            char[] result = new char[length];

            while (true)
            {
                csp.GetBytes(bytes);
                // Obtain the character of the class for each random byte
                for (int i = 0; i < length; i++)
                    result[i] = allchars[bytes[i] % allchars.Length];

                // Verify that it does not start or end with whitespace
                if (Char.IsWhiteSpace(result[0]) || Char.IsWhiteSpace(result[(length - 1) % length]))
                    continue;

                string testResult = new string(result);
                // Verify that all character classes are represented
                if (0 != classes.Take(complexity).Count(c => testResult.IndexOfAny(c) < 0))
                    continue;

                return testResult;
            }
        }
开发者ID:nilekshdhimer,项目名称:demos,代码行数:60,代码来源:PasswordEncrypt.aspx.cs

示例12: GenerateAes

        void GenerateAes()
        {
            var rng = new RNGCryptoServiceProvider();

            Globals.AesKey = new byte[16];
            Globals.AesIV = new byte[16];

            rng.GetBytes(Globals.AesKey);
            rng.GetBytes(Globals.AesIV);
        }
开发者ID:brownj,项目名称:SqrlNet,代码行数:10,代码来源:Global.asax.cs

示例13: AesEncryptor

        /// <summary>
        /// Creates AES instance
        /// </summary>
        public AesEncryptor()
        {
            aes = Aes.Create();
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(key);
                rng.GetBytes(iVec);
            }

            aes.IV = iVec;
            aes.Key = key;
            aes.Padding = PaddingMode.Zeros;
        }
开发者ID:Arcidev,项目名称:Arci.Networking,代码行数:16,代码来源:AesEncryptor.cs

示例14: GetRandomBytes

		/// <summary>
		/// Creates an array of bytes with a cryptographically strong sequence of random values.
		/// </summary>
		/// <param name="length">Length of array to create.</param>
		/// <returns>An array of bytes filled with a cryptographically strong sequence of random values.</returns>
		public static byte[] GetRandomBytes(int length)
		{
			byte[] randomBytes = new byte[length];
			RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
			rng.GetBytes(randomBytes);
			return randomBytes;
		}
开发者ID:Injac,项目名称:SocketIO.NetMF,代码行数:12,代码来源:CryptoUtils.cs

示例15: GenerateSalt

        /// <summary>
        /// Generate Password Salt Int to add to password
        /// </summary>
        /// <returns>Salt Int</returns>

        internal string GenerateSalt()
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[32];
            rng.GetBytes(buff);
            return Convert.ToBase64String(buff);
        }
开发者ID:ChrisNelsonPE,项目名称:surveyproject_main_public,代码行数:12,代码来源:User.cs


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