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


C# RandomNumberGenerator.GetBytes方法代码示例

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


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

示例1: GenerateRandomInt32Value

 private static int GenerateRandomInt32Value(RandomNumberGenerator randomNumberGenerator)
 {
     var fourRandomBytes = new byte[4]; // 4 bytes = 32 bits = Int32
     randomNumberGenerator.GetBytes(fourRandomBytes);
     var randomInt32Value = BitConverter.ToInt32(fourRandomBytes, 0);
     return randomInt32Value;
 }
开发者ID:NikolayIT,项目名称:CSharp-Tips-and-Tricks,代码行数:7,代码来源:HighQualityRandomNumbers.cs

示例2: AHAddress

 /**
  * Return a random AHAddress initialized from the given rng
  */
 public AHAddress(RandomNumberGenerator rng)
 {
   byte[] buffer = new byte[MemSize];
   rng.GetBytes(buffer);
   SetClass(buffer, this.Class);
   _buffer = MemBlock.Reference(buffer, 0, MemSize);
   _prefix = (uint)NumberSerializer.ReadInt(_buffer, 0);
 }
开发者ID:johnynek,项目名称:brunet,代码行数:11,代码来源:AHAddress.cs

示例3: CreateSalt

 public string CreateSalt()
 {
     using (_generator = _generatorInitializer())
     {
         var byteArr = new byte[32];
         _generator.GetBytes(byteArr);
         return Convert.ToBase64String(byteArr);
     }
 }
开发者ID:pt12lol,项目名称:pt12lol-mvc4application,代码行数:9,代码来源:AuthenticationHelper.cs

示例4: IsProbablePrime

        public static bool IsProbablePrime(this BigInteger source, int certainty, RandomNumberGenerator random)
        {
            if (source == 2 || source == 3)
                return true;
            if (source < 2 || source % 2 == 0)
                return false;

            BigInteger d = source - 1;
            int s = 0;

            while (d % 2 == 0)
            {
                d /= 2;
                s += 1;
            }

            if (random == null)
            {
                random = Randomizer.GetRandom();
            }

            byte[] bytes = new byte[(source.BitLength() + 7) / 8];
            BigInteger a;

            for (int i = 0; i < certainty; i++)
            {
                do
                {
                    random.GetBytes(bytes);
                    //bytes[bytes.Length - 1] = 0;
                    a = new BigInteger(bytes);
                }
                while (a < 2 || a >= source - 2);

                BigInteger x = BigInteger.ModPow(a, d, source);
                if (x == 1 || x == source - 1)
                    continue;

                for (int r = 1; r < s; r++)
                {
                    x = BigInteger.ModPow(x, 2, source);
                    if (x == 1)
                        return false;
                    if (x == source - 1)
                        break;
                }

                if (x != source - 1)
                    return false;
            }

            return true;
        }
开发者ID:Joopie1994,项目名称:HabboEncryption,代码行数:53,代码来源:BigIntegerPrime.cs

示例5: Create

		internal static string Create (RandomNumberGenerator rng)
		{
			if (rng == null)
				throw new ArgumentNullException ("rng");
			
			byte[] key = new byte [half_len];

			lock (rng) {
				rng.GetBytes (key);
			}
			return Encode (key);
		}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:12,代码来源:SessionId.cs

示例6: Random

        private static int Random(byte[] fourBytes, RandomNumberGenerator rng, int min, int max) {
            if (null == rng) throw new ArgumentNullException("rng");
            var scale = uint.MaxValue;
            while (scale == uint.MaxValue) {
                // Get four random bytes.
                rng.GetBytes(fourBytes);

                // Convert that into an uint.
                scale = BitConverter.ToUInt32(fourBytes, 0);
            }

            // Add min to the scaled difference between max and min.
            return (int)(min + (max - min) * (scale / (double)uint.MaxValue));
        }
开发者ID:kyourek,项目名称:Ensues.Security,代码行数:14,代码来源:PasswordGenerator.cs

示例7: GeneratePseudoPrime

        public static BigInteger GeneratePseudoPrime(int bitLength, int certainty, RandomNumberGenerator random)
        {
            byte[] bytes = new byte[(bitLength + 7) / 8];

            BigInteger result = 0;
            do
            {
                random.GetBytes(bytes);
                bytes[bytes.Length - 1] = 0;
                result = new BigInteger(bytes);
            }
            while (result.IsProbablePrime(certainty, random));

            return result;
        }
开发者ID:Joopie1994,项目名称:HabboEncryption,代码行数:15,代码来源:BigIntegerPrime.cs

示例8: HashPasswordV3

    private static byte[] HashPasswordV3(string password, RandomNumberGenerator rng, KeyDerivationPrf prf, int iterCount, int saltSize, int numBytesRequested) {
      // Produce a version 3 (see comment above) text hash.
      byte[] salt = new byte[saltSize];
      rng.GetBytes(salt);
      byte[] subkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, numBytesRequested);

      var outputBytes = new byte[13 + salt.Length + subkey.Length];
      outputBytes[0] = 0x01; // format marker
      WriteNetworkByteOrder(outputBytes, 1, (uint)prf);
      WriteNetworkByteOrder(outputBytes, 5, (uint)iterCount);
      WriteNetworkByteOrder(outputBytes, 9, (uint)saltSize);
      Buffer.BlockCopy(salt, 0, outputBytes, 13, salt.Length);
      Buffer.BlockCopy(subkey, 0, outputBytes, 13 + saltSize, subkey.Length);
      return outputBytes;
    }
开发者ID:grrizzly,项目名称:eventsourced.net,代码行数:15,代码来源:PasswordHasher.cs

示例9: SymmetricEncryption

    /// <summary>Creates a new SymmetricEncryption handler for the passed in
    /// SymmetricAlgorithm.</summary>
    public SymmetricEncryption(SymmetricAlgorithm Algorithm)
    {
      if(Algorithm.Mode != CipherMode.CBC) {
        throw new Exception("SymmetricEncryption requires the symmetric algorithm to use CBC.");
      }

      rng = new RNGCryptoServiceProvider();
      _sa = Algorithm;
      // We take care of PKCS7 padding here due to issues in the underlying implementations...
      _sa.Padding = PaddingMode.None;
      BlockSizeByte = _sa.BlockSize / 8;
      // Match the same size as our Window size...
      _decryptors = new Cache(64);
      _enc_iv = new byte[BlockSizeByte];
      rng.GetBytes(_enc_iv);
      _enc = _sa.CreateEncryptor(_sa.Key, _enc_iv);
      _temp = new byte[BlockSizeByte];
    }
开发者ID:kyungyonglee,项目名称:BrunetTutorial,代码行数:20,代码来源:SymmetricEncryption.cs

示例10: OneTimeToken

		/// <summary>
		/// Initializes a new instance of the <see cref="OneTimeToken"/> class.
		/// Creates a new token for Verification 
		/// </summary>
		/// <param name="key">The key.</param>
		/// <exception cref="System.ArgumentNullException"></exception>
		public OneTimeToken(byte[] key)
		{
			if (key != null || key.Length <= 0)
			{
				_hmacSha = new HMACSHA256(key);

				TokenStamp = new byte[128];

				_rng = System.Security.Cryptography.RandomNumberGenerator.Create();

				_rng.GetBytes(TokenStamp);

				_issueTime = DateTimeOffset.UtcNow;
			}
			else
			{
				throw new ArgumentNullException(nameof(key));
			}
		}
开发者ID:clarkis117,项目名称:GenericMvcUtilities,代码行数:25,代码来源:OneTimeToken.cs

示例11: GenPriv

 public BigInt GenPriv(RandomNumberGenerator rng)
 {
     EllipticCurve.BigInt priv = null;
     do
     {
         if (priv != null)
             priv.Clear();
         var bytes = new byte[curveByteLen];
         rng.GetBytes(bytes);
         var byteMask = (1 << (curveLen & 7)) - 1;
         if (byteMask != 0)
             bytes[0] &= (byte)byteMask;
         priv = new EllipticCurve.BigInt(bytes, 0, bytes.Length);
         Utils.ClearArray(bytes);
     } while (priv >= p || priv.IsZero());
     return priv;
 }
开发者ID:kraaden,项目名称:npgsql,代码行数:17,代码来源:EllipticCurve.cs

示例12: RsaOaepEncrypt

        [System.Security.SecurityCritical]  // auto-generated
        internal static byte[] RsaOaepEncrypt (RSA rsa, HashAlgorithm hash, PKCS1MaskGenerationMethod mgf, RandomNumberGenerator rng, byte[] data) {
            int cb = rsa.KeySize / 8;

            //  1. Hash the parameters to get PHash
            int cbHash = hash.HashSize / 8;
            if ((data.Length + 2 + 2*cbHash) > cb)
                throw new CryptographicException(String.Format(null, Environment.GetResourceString("Cryptography_Padding_EncDataTooBig"), cb-2-2*cbHash));
            hash.ComputeHash(EmptyArray<Byte>.Value); // Use an empty octet string

            //  2.  Create DB object
            byte[] DB = new byte[cb - cbHash];

            //  Structure is as follows:
            //      pHash || PS || 01 || M
            //      PS consists of all zeros

            Buffer.InternalBlockCopy(hash.Hash, 0, DB, 0, cbHash);
            DB[DB.Length - data.Length - 1] = 1;
            Buffer.InternalBlockCopy(data, 0, DB, DB.Length-data.Length, data.Length);

            // 3. Create a random value of size hLen
            byte[] seed = new byte[cbHash];
            rng.GetBytes(seed);

            // 4.  Compute the mask value
            byte[] mask = mgf.GenerateMask(seed, DB.Length);

            // 5.  Xor maskDB into DB
            for (int i=0; i < DB.Length; i++) {
                DB[i] = (byte) (DB[i] ^ mask[i]);
            }

            // 6.  Compute seed mask value
            mask = mgf.GenerateMask(DB, cbHash);

            // 7.  Xor mask into seed
            for (int i=0; i < seed.Length; i++) {
                seed[i] ^= mask[i];
            }

            // 8. Concatenate seed and DB to form value to encrypt
            byte[] pad = new byte[cb];
            Buffer.InternalBlockCopy(seed, 0, pad, 0, seed.Length);
            Buffer.InternalBlockCopy(DB, 0, pad, seed.Length, DB.Length);

            return rsa.EncryptValue(pad);
        }
开发者ID:peterdocter,项目名称:referencesource,代码行数:48,代码来源:utils.cs

示例13: Encrypt_OAEP

		// PKCS #1 v.2.1, Section 7.1.1
		// RSAES-OAEP-ENCRYPT ((n, e), M, L)
		public static byte[] Encrypt_OAEP (RSA rsa, HashAlgorithm hash, RandomNumberGenerator rng, byte[] M) 
		{
			int size = rsa.KeySize / 8;
			int hLen = hash.HashSize / 8;
			if (M.Length > size - 2 * hLen - 2)
				throw new CryptographicException ("message too long");
			// empty label L SHA1 hash
			byte[] lHash = GetEmptyHash (hash);
			int PSLength = (size - M.Length - 2 * hLen - 2);
			// DB = lHash || PS || 0x01 || M
			byte[] DB = new byte [lHash.Length + PSLength + 1 + M.Length];
			Buffer.BlockCopy (lHash, 0, DB, 0, lHash.Length);
			DB [(lHash.Length + PSLength)] = 0x01;
			Buffer.BlockCopy (M, 0, DB, (DB.Length - M.Length), M.Length);
	
			byte[] seed = new byte [hLen];
			rng.GetBytes (seed);
	
			byte[] dbMask = MGF1 (hash, seed, size - hLen - 1);
			byte[] maskedDB = xor (DB, dbMask);
			byte[] seedMask = MGF1 (hash, maskedDB, hLen);
			byte[] maskedSeed = xor (seed, seedMask);
			// EM = 0x00 || maskedSeed || maskedDB
			byte[] EM = new byte [maskedSeed.Length + maskedDB.Length + 1];
			Buffer.BlockCopy (maskedSeed, 0, EM, 1, maskedSeed.Length);
			Buffer.BlockCopy (maskedDB, 0, EM, maskedSeed.Length + 1, maskedDB.Length);
	
			byte[] m = OS2IP (EM);
			byte[] c = RSAEP (rsa, m);
			return I2OSP (c, size);
		}
开发者ID:Jakosa,项目名称:MonoLibraries,代码行数:33,代码来源:PKCS1.cs

示例14: Observe

        /// <summary>
        /// When one Adds a key to a binomial sketch, a random bit among the subset of k that are currently 0 (false)
        /// will be set to 1 (true).
        /// To ensure roughly half the bits remain zero at all times, a random index from the subset of all k bits that
        /// are currently 1 (true) will be set to 0 (false).
        /// </summary>
        /// <param name="key">The key to add to the set.</param>
        /// <param name="rng">Optionally passing a RandomNumberGenerator should improve performance as it will
        /// save the Observe operation from having to create one. (RandomNumberGenerators are not thread safe, and
        /// should not be used between Tasks/Threads.)</param>
        /// <returns>Of the bits at the indices for the given key, the number of bits that were set to 1 (true)
        /// before the Observe operation.  The maximum possible value to be returned, if all bits were already
        /// set to 1 (true) would be NumberOfIndexes.  If a key has not been seen before, the expected (average)
        /// result is NumberOfIndexes/2, but will vary with the binomial distribution.</returns>
        public int Observe(string key, RandomNumberGenerator rng = null)
        {
            // Get a list of indexes that are not yet set
            List<int> indexesUnset = GetUnsetIndexesForKey(key).ToList();

            // We can only update state to record the observation if there is an unset (0) index that we can set (to 1).
            if (indexesUnset.Count > 0)
            {
                NumberOfObservations++;

                // Create a random number generator if one was not provided by the caller.
                rng = rng ?? RandomNumberGenerator.Create();

                // We'll need the randomness to determine which bit to set and which to clear
                byte[] randBytes = new byte[8];
                rng.GetBytes(randBytes);

                // First, pick a random index to set by appling the last of the universal hash functions
                // to the random bytes
                int indexToSet =
                    indexesUnset[ (int) ( _universalHashFunctions[_universalHashFunctions.Length - 1].Hash(randBytes) %
                                          (uint) indexesUnset.Count ) ];

                // Next, pick the index to clear by applying hash functions to the random bytes until we reach
                // an index that is set.  (For any reasonable sized number of indexes (e.g., >= 30), the probability
                // that we would reach the last hash function used earlier, or run out of hash functions, is so small
                // as to be something we can ignore.)
                int indexToClear = 0;
                foreach (var hashFunction in _universalHashFunctions)
                {
                    indexToClear = (int) ( hashFunction.Hash(randBytes) % (uint) SizeInBits);
                    if (_sketch[indexToClear])
                        // We break when we've found an index to a bit that is set and so can be cleared to 0/false.
                        break;
                }
                _sketch[indexToClear] = false;
                _sketch[indexToSet] = true;
            }

            // The number of bits set to 1/true is the number that were not 0/false.
            return NumberOfIndexes - indexesUnset.Count;
        }
开发者ID:Johnunc,项目名称:StopGuessing,代码行数:56,代码来源:BinomialSketch.cs

示例15: RsaOaepEncrypt

 internal static byte[] RsaOaepEncrypt(RSA rsa, HashAlgorithm hash, PKCS1MaskGenerationMethod mgf, RandomNumberGenerator rng, byte[] data)
 {
     int num = rsa.KeySize / 8;
     int byteCount = hash.HashSize / 8;
     if (((data.Length + 2) + (2 * byteCount)) > num)
     {
         throw new CryptographicException(string.Format(null, Environment.GetResourceString("Cryptography_Padding_EncDataTooBig"), new object[] { (num - 2) - (2 * byteCount) }));
     }
     hash.ComputeHash(new byte[0]);
     byte[] dst = new byte[num - byteCount];
     Buffer.InternalBlockCopy(hash.Hash, 0, dst, 0, byteCount);
     dst[(dst.Length - data.Length) - 1] = 1;
     Buffer.InternalBlockCopy(data, 0, dst, dst.Length - data.Length, data.Length);
     byte[] buffer2 = new byte[byteCount];
     rng.GetBytes(buffer2);
     byte[] buffer3 = mgf.GenerateMask(buffer2, dst.Length);
     for (int i = 0; i < dst.Length; i++)
     {
         dst[i] = (byte) (dst[i] ^ buffer3[i]);
     }
     buffer3 = mgf.GenerateMask(dst, byteCount);
     for (int j = 0; j < buffer2.Length; j++)
     {
         buffer2[j] = (byte) (buffer2[j] ^ buffer3[j]);
     }
     byte[] buffer4 = new byte[num];
     Buffer.InternalBlockCopy(buffer2, 0, buffer4, 0, buffer2.Length);
     Buffer.InternalBlockCopy(dst, 0, buffer4, buffer2.Length, dst.Length);
     return rsa.EncryptValue(buffer4);
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:30,代码来源:Utils.cs


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