GetBytes() public abstract method

public abstract GetBytes ( byte data ) : void
data byte
return void
Ejemplo n.º 1
0
 public void fill(byte[] foo, int start, int len)
 {
     while (len > tmp.Length)
     {
         rng.GetBytes(tmp);
         Array.Copy(tmp, 0, foo, start, tmp.Length);
         len   -= tmp.Length;
         start += tmp.Length;
     }
     rng.GetBytes(tmp);
     Array.Copy(tmp, 0, foo, start, len);
 }
Ejemplo n.º 2
0
        public static byte[] Generate(int length)
        {
            if (length < 1)
            {
                throw new ArgumentOutOfRangeException("length");
            }

            var bytes = new byte[length];

            _random.GetBytes(bytes);
            return(bytes);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Generate a random IV.
 /// </summary>
 /// <returns></returns>
 private static byte[] IV()
 {
     byte[] data = new byte[IV_SIZE];
     System.Security.Cryptography.RandomNumberGenerator rnd = System.Security.Cryptography.RandomNumberGenerator.Create();
     rnd.GetBytes(data);
     return(data);
 }
Ejemplo n.º 4
0
        public static string CreateHash(string password)
        {
            // Generate a random salt
            byte[] salt = new byte[SALT_BYTES];
            try {
                using (System.Security.Cryptography.RandomNumberGenerator csprng = System.Security.Cryptography.RandomNumberGenerator.Create()) {
                    csprng.GetBytes(salt);
                }
            } catch (CryptographicException ex) {
                throw new CannotPerformOperationException(
                          "Random number generator not available.",
                          ex
                          );
            } catch (ArgumentNullException ex) {
                throw new CannotPerformOperationException(
                          "Invalid argument given to random number generator.",
                          ex
                          );
            }

            byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTES);

            // format: algorithm:iterations:hashSize:salt:hash
            String parts = "sha1:" +
                           PBKDF2_ITERATIONS +
                           ":" +
                           hash.Length +
                           ":" +
                           Convert.ToBase64String(salt) +
                           ":" +
                           Convert.ToBase64String(hash);

            return(parts);
        }
Ejemplo n.º 5
0
    double NextDouble()
    {
        rand.GetBytes(random);
        rng_ = BitConverter.ToUInt32(random, 0);

        return((rng_ - min_) / (max_ - min_ + 1));
    }
 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;
 }
Ejemplo n.º 7
0
 /**
  * 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);
 }
 public string CreateSalt()
 {
     using (_generator = _generatorInitializer())
     {
         var byteArr = new byte[32];
         _generator.GetBytes(byteArr);
         return Convert.ToBase64String(byteArr);
     }
 }
        /// <summary>
        /// Generate cryptographically random key of given bit size.
        /// </summary>
        /// <param name="size">The size.</param>
        /// <returns> the key </returns>
        private static string GenerateRandomKey(int size)
        {
            byte[] key = new byte[(int)size / 8];
#if FullNetFx
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
#else
            System.Security.Cryptography.RandomNumberGenerator crypto = System.Security.Cryptography.RandomNumberGenerator.Create();
#endif
            crypto.GetBytes(key);
            return(Convert.ToBase64String(key));
        }
Ejemplo n.º 10
0
		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);
		}
Ejemplo n.º 11
0
        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;
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Gets the next available random integer using a Pseudo<see cref="RandomNumberGenerator"/> to generate random bytes
 /// </summary>
 /// <returns></returns>
 public static int GetPrngInt()
 {
     byte[] buffer  = new byte[System.Runtime.InteropServices.Marshal.SizeOf(typeof(int))];
     byte[] buffer2 = new byte[buffer.Length];
     prng.GetNonZeroBytes(buffer);
     prng.GetBytes(buffer2);
     for (int i = 0; i < buffer.Length; i++)
     {
         buffer[i] ^= buffer2[(buffer.Length - 1) - i];
     }
     return(System.BitConverter.ToInt32(buffer, 0));
 }
Ejemplo n.º 13
0
        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));
        }
Ejemplo n.º 14
0
        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;
        }
Ejemplo n.º 15
0
    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;
    }
Ejemplo n.º 16
0
        private void btnselnumberchars_Click(object sender, EventArgs e)
        {
            R randgen = R.Create();

            byte[] rand = new byte[10];

            randgen.GetBytes(rand);
            // Random Number between 0 - 255 --- we need between 0 - chars2generate
            int startselection = (int)Math.Floor(rand[2] * (rtbseedgen.TextLength - cbbNumChars.SelectedIndex + 1) / 255.0);

            if (startselection < 0)
            {
                startselection = 0;
            }
            rtbseedgen.Select(startselection, cbbNumChars.SelectedIndex + 1);
            rtbseedgen.Focus();
        }
Ejemplo n.º 17
0
        public static string StrRandomNumber(int length)
        {
            System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create();
            byte[] buffer1 = new byte[length];
            rng.GetBytes(buffer1);
            rng = null;

            string        str = "0123456789";
            StringBuilder s   = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                Random rnd = new Random(buffer1[i]);
                int    w   = rnd.Next(0, str.Length);
                s.Append(str.Substring(w, 1));
            }
            return(s.ToString());
        }
    /// <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];
    }
Ejemplo n.º 19
0
		/// <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));
			}
		}
 internal static BigInteger NextBigInteger(this System.Security.Cryptography.RandomNumberGenerator rng, int sizeInBits)
 {
     if (sizeInBits < 0)
     {
         throw new ArgumentException("sizeInBits must be non-negative");
     }
     if (sizeInBits == 0)
     {
         return(0);
     }
     byte[] b = new byte[sizeInBits / 8 + 1];
     rng.GetBytes(b);
     if (sizeInBits % 8 == 0)
     {
         b[b.Length - 1] = 0;
     }
     else
     {
         b[b.Length - 1] &= (byte)((1 << sizeInBits % 8) - 1);
     }
     return(new BigInteger(b));
 }
Ejemplo n.º 21
0
    void RandomExample()
    {
        {
            Random rng = new Random();
            Console.WriteLine(rng.Next().ToString());
            Console.WriteLine(rng.Next().ToString());
            Console.WriteLine(rng.Next().ToString());
        }

        Console.WriteLine();

        for (int i = 0; i < 2; i++)
        {
            Random rngSeed = new Random(1); // Pro = reproducablility
            Console.WriteLine(rngSeed.Next().ToString());
            Console.WriteLine(rngSeed.Next().ToString());

            Console.WriteLine("-");
        }

        Console.WriteLine();

        for (int i = 0; i < 100; i++)
        { // Approx 10 ms between need Random seeds
            Console.WriteLine(new Random().Next().ToString());
        }

        Console.WriteLine();

        System.Security.Cryptography.RandomNumberGenerator rngPlusPlus
            = System.Security.Cryptography.RandomNumberGenerator.Create();
        byte[] randomData = new byte[4];
        Console.WriteLine(randomData[0]);
        rngPlusPlus.GetBytes(randomData);
        Console.WriteLine(randomData[0]);
    }
Ejemplo n.º 22
0
 public override void GetBytes(byte[] data) => _impl.GetBytes(data);
Ejemplo n.º 23
0
		// 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);
		}
Ejemplo n.º 24
0
 public static void GetBytes(byte[] bytes)
 {
     LocalRandomNumberGenerator.GetBytes(bytes);
 }
Ejemplo n.º 25
0
        /// <include file='doc\RSAOAEPKeyExchangeFormatter.uex' path='docs/doc[@for="RSAOAEPKeyExchangeFormatter.CreateKeyExchange"]/*' />
        public override byte[] CreateKeyExchange(byte[] rgbData)
        {
            byte[] rgbKeyEx;

            if (_rsaKey is RSACryptoServiceProvider)
            {
                rgbKeyEx = ((RSACryptoServiceProvider)_rsaKey).Encrypt(rgbData, true);
            }
            else
            {
                int                  cb = _rsaKey.KeySize / 8;
                int                  cbHash;
                HashAlgorithm        hash;
                int                  i;
                MaskGenerationMethod mgf;
                byte[]               rgbDB;
                byte[]               rgbIn;
                byte[]               rgbMask;
                byte[]               rgbSeed;

                //  Create the OAEP padding object.

                //  1.  Hash the parameters to get rgbPHash

                hash   = (HashAlgorithm)CryptoConfig.CreateFromName("SHA1"); // Create the default SHA1 object
                cbHash = hash.HashSize / 8;
                if ((rgbData.Length + 2 + 2 * cbHash) > cb)
                {
                    throw new CryptographicException(String.Format(Environment.GetResourceString("Cryptography_Padding_EncDataTooBig"), cb - 2 - 2 * cbHash));
                }
                hash.ComputeHash(new byte[0]); // Use an empty octet string

                //  2.  Create DB object

                rgbDB = new byte[cb - cbHash - 1];

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

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

                // 3. Create a random value of size hLen

                if (RngValue == null)
                {
                    RngValue = RandomNumberGenerator.Create();
                }

                rgbSeed = new byte[cbHash];
                RngValue.GetBytes(rgbSeed);

                // 4.  Compute the mask value

                mgf = new PKCS1MaskGenerationMethod();

                rgbMask = mgf.GenerateMask(rgbSeed, rgbDB.Length);

                // 5.  Xor rgbMaskDB into rgbDB

                for (i = 0; i < rgbDB.Length; i++)
                {
                    rgbDB[i] = (byte)(rgbDB[i] ^ rgbMask[i]);
                }

                // 6.  Compute seed mask value

                rgbMask = mgf.GenerateMask(rgbDB, cbHash);

                // 7.  Xor rgbMask into rgbSeed

                for (i = 0; i < rgbSeed.Length; i++)
                {
                    rgbSeed[i] ^= rgbMask[i];
                }

                // 8. Concatenate rgbSeed and rgbDB to form value to encrypt

                rgbIn = new byte[cb];
                Buffer.InternalBlockCopy(rgbSeed, 0, rgbIn, 1, rgbSeed.Length);
                Buffer.InternalBlockCopy(rgbDB, 0, rgbIn, rgbSeed.Length + 1, rgbDB.Length);

                // 9.  Now Encrypt it

                rgbKeyEx = _rsaKey.EncryptValue(rgbIn);
            }
            return(rgbKeyEx);
        }
 /// <inheritdoc/>
 public override void GetBytes(byte[] buffer)
 {
     RandomSource.GetBytes(buffer);
 }
Ejemplo n.º 27
0
    // The 'Number' base class has a static method 'Random' which only requires
    // a 'numBits' argument (the random number generator is given as a private
    // field of the class). Therefore, the following static method (which
    // requires two arguments) is not seen as an override. Hence no 'new' keyword.
    public static Number Random(int numBits, Random rnd)
    {
        // working out required number of bytes
        // 0 bit  -> 0 byte
        // 1 bit  -> 1 byte
        // ...
        // 8 bits -> 1 byte
        // 9 bits -> 2 bytes
        // ...

        int len = (numBits + 7) / 8;

        if(len == 0) return Number2.ZERO;

        byte[] bytes = new byte[len];

        rnd.GetBytes(bytes);  // random number generation

        // we may have generated too many bits. The leading bits of our big-endian
        // representation needs to be set to 0 so as to reflect numBits exactly.

        int diff = len * 8 - numBits;         // number of leading bits set to 0

        int mask = 0x7f;                      // 0111 1111 in binary

        // we want to regard out 'bytes' array as a big-endian representation,
        // so the leading byte is bytes[0], which is the one needing adjustment

        while(diff > 0)
        {
          bytes[0] = (byte) (bytes[0] & mask);  // setting leading byte to 0

          mask = mask >> 1;

          --diff;
        }

        return Number2.FromBytes(1, bytes);
    }
 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);
 }
Ejemplo n.º 29
0
        [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);
        }
Ejemplo n.º 30
0
 public sealed override void GenerateKey()
 {
     Key = RandomNumberGenerator.GetBytes(KeySize / BitsPerByte);
 }
	// Encrypt a value using a specified OAEP padding array.
	// The array may be null to pad with zeroes.
	internal byte[] EncryptOAEP(byte[] rgb, byte[] padding,
								RandomNumberGenerator rng)
			{
				// Check the data against null.
				if(rgb == null)
				{
					throw new ArgumentNullException("rgb");
				}

				// Make sure that we have sufficient RSA parameters.
				if(rsaParams.Modulus == null)
				{
					throw new CryptographicException
						(_("Crypto_RSAParamsNotSet"));
				}

				// Format the label, padding string, and rgb into a message.
				int k = rsaParams.Modulus.Length;
				if(rgb.Length > (k - 2 * 20 - 2))
				{
					throw new CryptographicException
						(_("Crypto_RSAMessageTooLong"));
				}
				byte[] msg = new byte [k - 20 - 1];
				int posn = 0;
				Array.Copy(label, 0, msg, posn, 20);
				posn += 20;
				int padlen = k - rgb.Length - 2 * 20 - 2;
				if(padlen > 0 && padding != null)
				{
					if(padding.Length <= padlen)
					{
						Array.Copy(padding, 0, msg, posn, padding.Length);
					}
					else
					{
						Array.Copy(padding, 0, msg, posn, padlen);
					}
				}
				posn += padlen;
				msg[posn++] = (byte)0x01;
				Array.Copy(rgb, 0, msg, posn, rgb.Length);

				// Acquire a mask generation method, based on SHA-1.
				MaskGenerationMethod maskGen = new PKCS1MaskGenerationMethod();

				// Generate a random seed to use to generate masks.
				byte[] seed = new byte [20];
				rng.GetBytes(seed);

				// Generate a mask and encrypt the above message.
				byte[] mask = maskGen.GenerateMask(seed, msg.Length);
				int index;
				for(index = 0; index < msg.Length; ++index)
				{
					msg[index] ^= mask[index];
				}

				// Generate another mask and encrypt the seed.
				byte[] seedMask = maskGen.GenerateMask(msg, 20);
				for(index = 0; index < 20; ++index)
				{
					seed[index] ^= seedMask[index];
				}

				// Build the value to be encrypted using RSA.
				byte[] value = new byte [k];
				Array.Copy(seed, 0, value, 1, 20);
				Array.Copy(msg, 0, value, 21, msg.Length);

				// Encrypt the value.
				byte[] encrypted = ApplyPublic(value);

				// Destroy sensitive data.
				Array.Clear(msg, 0, msg.Length);
				Array.Clear(seed, 0, seed.Length);
				Array.Clear(mask, 0, mask.Length);
				Array.Clear(seedMask, 0, seedMask.Length);
				Array.Clear(value, 0, value.Length);

				// Done.
				return encrypted;
			}
 public override void GenerateIV()
 {
     IVValue = RandomNumberGenerator.GetBytes(8);
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Generate a salt for use with the BCrypt.HashPassword() method.
        /// </summary>
        /// <param name="logRounds">The log2 of the number of rounds of
        /// hashing to apply. The work factor therefore increases as (2 **
        /// logRounds).</param>
        /// <param name="random">An instance of RandomNumberGenerator to use.</param>
        /// <returns>An encoded salt value.</returns>
        public static string GenerateSalt(int logRounds, RandomNumberGenerator random)
        {
            byte[] randomBytes = new byte[BCRYPT_SALT_LEN];

            random.GetBytes(randomBytes);

            StringBuilder rs = new StringBuilder((randomBytes.Length * 2) + 8);

            rs.Append("$2a$");
            if (logRounds < 10)
            {
                rs.Append('0');
            }
            rs.Append(logRounds);
            rs.Append('$');
            rs.Append(EncodeBase64(randomBytes, randomBytes.Length));

            return rs.ToString();
        }
 public static uint RandomUInt32(this RandomNumberGenerator random)
 {
     byte[] buffer = new byte[4];
     random.GetBytes(buffer);
     return(BitConverter.ToUInt32(buffer, 0));
 }
Ejemplo n.º 35
0
 internal static string GenerateToken(RandomNumberGenerator generator)
 {
     var data = new byte[0x10];
     generator.GetBytes(data);
     return HttpServerUtility.UrlTokenEncode(data);
 }
Ejemplo n.º 36
0
        /// <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;
        }
 public static ulong RandomUInt64(this RandomNumberGenerator random)
 {
     byte[] buffer = new byte[8];
     random.GetBytes(buffer);
     return(BitConverter.ToUInt64(buffer, 0));
 }
Ejemplo n.º 38
0
 public HMACSHA512()
     : this(RandomNumberGenerator.GetBytes(BlockSize))
 {
 }
Ejemplo n.º 39
0
 private static byte[] GetRandomBytes(RandomNumberGenerator rng, int byteCount)
 {
     byte[] bytes = new byte[byteCount];
     rng.GetBytes(bytes);
     return bytes;
 }
Ejemplo n.º 40
0
 internal static string GenerateToken(RandomNumberGenerator generator)
 {
     byte[] tokenBytes = new byte[TokenSizeInBytes];
     generator.GetBytes(tokenBytes);
     return HttpServerUtility.UrlTokenEncode(tokenBytes);
 }
Ejemplo n.º 41
0
 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;
 }
Ejemplo n.º 42
0
 public override void GenerateIV()
 {
     IV = RandomNumberGenerator.GetBytes(BlockSize / BitsPerByte);
 }
Ejemplo n.º 43
0
 // Generates a new 80-bit security token
 public static byte[] GenerateRandomKey()
 {
     byte[] bytes = new byte[20];
     _rng.GetBytes(bytes);
     return(bytes);
 }
Ejemplo n.º 44
0
        /// <summary>
        ///     Randomizes the bits in "this" from the specified RNG.
        /// </summary>
        /// <param name="rng">A RNG.</param>
        public void Randomize(RandomNumberGenerator rng)
        {
            if (this == 0)
                return;

            int bits = BitCount();
            int dwords = bits >> 5;
            int remBits = bits & 0x1F;

            if (remBits != 0)
                dwords++;

            var random = new byte[dwords << 2];

            rng.GetBytes(random);
            Buffer.BlockCopy(random, 0, data, 0, dwords << 2);

            if (remBits != 0)
            {
                var mask = (uint)(0x01 << (remBits - 1));
                data[dwords - 1] |= mask;

                mask = 0xFFFFFFFF >> (32 - remBits);
                data[dwords - 1] &= mask;
            }

            else
                data[dwords - 1] |= 0x80000000;

            Normalize();
        }
Ejemplo n.º 45
0
        /// <summary>
        ///     Generates a new, random BigInteger of the specified length.
        /// </summary>
        /// <param name="bits">The number of bits for the new number.</param>
        /// <param name="rng">A random number generator to use to obtain the bits.</param>
        /// <returns>A random number of the specified length.</returns>
        public static BigInteger GenerateRandom(int bits, RandomNumberGenerator rng)
        {
            int dwords = bits >> 5;
            int remBits = bits & 0x1F;

            if (remBits != 0)
                dwords++;

            var ret = new BigInteger(Sign.Positive, (uint)dwords + 1);
            var random = new byte[dwords << 2];

            rng.GetBytes(random);
            Buffer.BlockCopy(random, 0, ret.data, 0, dwords << 2);

            if (remBits != 0)
            {
                var mask = (uint)(0x01 << (remBits - 1));
                ret.data[dwords - 1] |= mask;

                mask = 0xFFFFFFFF >> (32 - remBits);
                ret.data[dwords - 1] &= mask;
            }
            else
                ret.data[dwords - 1] |= 0x80000000;

            ret.Normalize();
            return ret;
        }
Ejemplo n.º 46
0
        // Encrypt a value using a specified OAEP padding array.
        // The array may be null to pad with zeroes.
        internal byte[] EncryptOAEP(byte[] rgb, byte[] padding,
                                    RandomNumberGenerator rng)
        {
            // Check the data against null.
            if (rgb == null)
            {
                throw new ArgumentNullException("rgb");
            }

            // Make sure that we have sufficient RSA parameters.
            if (rsaParams.Modulus == null)
            {
                throw new CryptographicException
                          (_("Crypto_RSAParamsNotSet"));
            }

            // Format the label, padding string, and rgb into a message.
            int k = rsaParams.Modulus.Length;

            if (rgb.Length > (k - 2 * 20 - 2))
            {
                throw new CryptographicException
                          (_("Crypto_RSAMessageTooLong"));
            }
            byte[] msg  = new byte [k - 20 - 1];
            int    posn = 0;

            Array.Copy(label, 0, msg, posn, 20);
            posn += 20;
            int padlen = k - rgb.Length - 2 * 20 - 2;

            if (padlen > 0 && padding != null)
            {
                if (padding.Length <= padlen)
                {
                    Array.Copy(padding, 0, msg, posn, padding.Length);
                }
                else
                {
                    Array.Copy(padding, 0, msg, posn, padlen);
                }
            }
            posn       += padlen;
            msg[posn++] = (byte)0x01;
            Array.Copy(rgb, 0, msg, posn, rgb.Length);

            // Acquire a mask generation method, based on SHA-1.
            MaskGenerationMethod maskGen = new PKCS1MaskGenerationMethod();

            // Generate a random seed to use to generate masks.
            byte[] seed = new byte [20];
            rng.GetBytes(seed);

            // Generate a mask and encrypt the above message.
            byte[] mask = maskGen.GenerateMask(seed, msg.Length);
            int    index;

            for (index = 0; index < msg.Length; ++index)
            {
                msg[index] ^= mask[index];
            }

            // Generate another mask and encrypt the seed.
            byte[] seedMask = maskGen.GenerateMask(msg, 20);
            for (index = 0; index < 20; ++index)
            {
                seed[index] ^= seedMask[index];
            }

            // Build the value to be encrypted using RSA.
            byte[] value = new byte [k];
            Array.Copy(seed, 0, value, 1, 20);
            Array.Copy(msg, 0, value, 21, msg.Length);

            // Encrypt the value.
            byte[] encrypted = ApplyPublic(value);

            // Destroy sensitive data.
            Array.Clear(msg, 0, msg.Length);
            Array.Clear(seed, 0, seed.Length);
            Array.Clear(mask, 0, mask.Length);
            Array.Clear(seedMask, 0, seedMask.Length);
            Array.Clear(value, 0, value.Length);

            // Done.
            return(encrypted);
        }
Ejemplo n.º 47
-1
 /**
  * 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);
 }