Example #1
0
 static int GetRandomSeed()
 {
     byte[] bytes = new byte[4];
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytes);
     return BitConverter.ToInt32(bytes, 0);
 }
Example #2
0
 public static string GenerateNewSalt()
 {
     byte[] saltInBytes = new byte[16];
        System.Security.Cryptography.RNGCryptoServiceProvider saltGenerator = new System.Security.Cryptography.RNGCryptoServiceProvider();
        saltGenerator.GetBytes(saltInBytes);
        return Convert.ToBase64String(saltInBytes);
 }
        public string GetNext(int length, char[] charSet)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length", "Length cannot be less than zero.");
            }

            const int byteSize = 0x100;
            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                var result = new StringBuilder();
                var buf = new byte[128];
                while (result.Length < length)
                {
                    rng.GetBytes(buf);
                    for (var i = 0; i < buf.Length && result.Length < length; ++i)
                    {
                        var outOfRangeStart = byteSize - (byteSize % charSet.Length);
                        if (outOfRangeStart <= buf[i]) continue;
                        result.Append(charSet[buf[i] % charSet.Length]);
                    }
                }
                return result.ToString();
            }
        }
Example #4
0
        /// <remarks>
        /// http://stackoverflow.com/questions/730268/unique-random-string-generation
        /// </remarks>
        string GenerateRandomString(int length,
            string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
        {
            if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), "length cannot be less than zero.");
            if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty.");

            const int byteSize = 0x100;
            var allowedCharSet = new HashSet<char>(allowedChars).ToArray();
            if (byteSize < allowedCharSet.Length)
                throw new ArgumentException($"allowedChars may contain no more than {byteSize} characters.");

            // Guid.NewGuid and System.Random are not particularly random. By using a
            // cryptographically-secure random number generator, the caller is always
            // protected, regardless of use.
            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                var result = new StringBuilder();
                var buf = new byte[128];
                while (result.Length < length)
                {
                    rng.GetBytes(buf);
                    for (var i = 0; i < buf.Length && result.Length < length; ++i)
                    {
                        // Divide the byte into allowedCharSet-sized groups. If the
                        // random value falls into the last group and the last group is
                        // too small to choose from the entire allowedCharSet, ignore
                        // the value in order to avoid biasing the result.
                        var outOfRangeStart = byteSize - (byteSize%allowedCharSet.Length);
                        if (outOfRangeStart <= buf[i]) continue;
                        result.Append(allowedCharSet[buf[i]%allowedCharSet.Length]);
                    }
                }
                return result.ToString();
            }
        }
Example #5
0
        System.Security.Cryptography.RNGCryptoServiceProvider rnd; // generator liczb pseudolosowych

        #endregion Fields

        #region Constructors

        public Ant()
        {
            mSize = 0;
            mPath = new List<int>();
            freeTasks = new List<int>();
            rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();
        }
Example #6
0
		static void Espresso_Publisher(ZContext context) 
		{
			// The publisher sends random messages starting with A-J:

			using (var publisher = new ZSocket(context, ZSocketType.PUB))
			{
				publisher.Bind("tcp://*:6000");

				ZError error;

				while (true)
				{
					var bytes = new byte[5];
					using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
					{
						rng.GetBytes(bytes);
					}

					if (!publisher.SendBytes(bytes, 0, bytes.Length, ZSocketFlags.None, out error))
					{
						if (error == ZError.ETERM)
							return;	// Interrupted
						throw new ZException(error);
					}

					Thread.Sleep(1);
				}
			}
		}
Example #7
0
 /// <summary>
 /// Create string salt
 /// </summary>
 /// <param name="grv">Create string salt</param>
 public static string CreateSalt()
 {
     byte[] bytSalt = new byte[9];
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytSalt);
     return Convert.ToBase64String(bytSalt);
 }
Example #8
0
		/// <summary>
		/// You are using ZContext.Current!
		/// </summary>
		public ZActor(ZAction0 action, params object[] args)
			: this(default(string), action, args)
		{
			var rnd0 = new byte[8];
			using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetNonZeroBytes(rnd0);
			this.Endpoint = string.Format("inproc://{0}", ZContext.Encoding.GetString(rnd0));
		}
Example #9
0
 public void TestOccasaionallyIgnored()
 {
     var rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();
     var buf = new byte[1];
     rnd.GetBytes(buf);
     if ( buf[0] > 100 ) Assert.Ignore("too big");
 }
Example #10
0
 static string GetNonceAsHexDigitString(int lengthInBytes)
 {
     var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     var bytes = new byte[lengthInBytes];
     rng.GetBytes(bytes);
     return ToHexDigitString(bytes);
 }
Example #11
0
        public static string Generate()
        {
            // Generate random
            var rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var entropy = new byte[bytes - 4];
            try {
                rnd.GetBytes(entropy);
            } finally {
                rnd.Dispose();
            }

            // Hash
            var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] hash;
            try {
                hash = sha.ComputeHash(entropy);
            } finally {
                sha.Dispose();
            }

            // Compute output
            var raw = new byte[bytes];
            Array.Copy(entropy, 0, raw, 0, bytes - 4);
            Array.Copy(hash, 0, raw, bytes - 4, 4);

            // Convert to Base64
            return Convert.ToBase64String(raw).Replace('+', '!').Replace('/', '~');
        }
        private static int GetRandomSeed()
        {
            var bytes = new byte[4];
            var rng   = new System.Security.Cryptography.RNGCryptoServiceProvider();

            rng.GetBytes(bytes);
            return(BitConverter.ToInt32(bytes, 0));
        }
Example #13
0
        /// <summary>
        /// Generate random Id. Uses System.Security.Cryptography.RNGCryptoServiceProvider
        /// </summary>
        /// <returns>New random Id</returns>
        public static KadId GenerateRandom()
        {
            var rnCryptoServiceProvider = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] key = new byte[20];
            rnCryptoServiceProvider.GetBytes(key);
            return(new KadId(key));
        }
Example #14
0
        public string CreateSalt()
        {
            byte[] bytSalt = new byte[16];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytSalt);

            return(Convert.ToBase64String(bytSalt));
        }
Example #15
0
 public Noise(int size, float Amp)
 {
     BuffSize         = size;
     Amplitude        = Amp;
     NoiseGen         = new System.Security.Cryptography.RNGCryptoServiceProvider();
     RandomNoiseBytes = new byte[size];
     Result           = new float[size];
 }
Example #16
0
        private static byte[] GenerateRandomBytes(int count)
        {
            var b = new byte[count];
            var c = new System.Security.Cryptography.RNGCryptoServiceProvider();

            c.GetNonZeroBytes(b);
            return(b);
        }
Example #17
0
        protected string CreateSalt(int size)
        {
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buff = new byte[size];
            rng.GetBytes(buff);

            return Convert.ToBase64String(buff);
        }
Example #18
0
 private static int GetNewSeed()
 {
     byte[] rndBytes = new byte[4];
     System.Security.Cryptography.RNGCryptoServiceProvider rng =
         new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(rndBytes);
     return(BitConverter.ToInt32(rndBytes, 0));
 }
Example #19
0
        public string CreateSalt(int size)
        {
            var rng  = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buff = new byte[size];

            rng.GetBytes(buff);
            return(Convert.ToBase64String(buff));
        }
Example #20
0
        public static String KrijoSalt(int madhesia)
        {
            var nrRastesishem = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var baferi        = new byte[madhesia];

            nrRastesishem.GetBytes(baferi);
            return(Convert.ToBase64String(baferi));
        }
        /// <summary>
        /// Return a string of random hexadecimal values which is 6 characters long and relatively unique.
        /// </summary>
        /// <returns></returns>
        /// <remarks>In testing, result was unique for at least 10,000,000 values obtained in a loop.
        /// https://stackoverflow.com/questions/36625891/create-a-unique-5-character-alphanumeric-string
        /// </remarks>
        public static string GetShortID()
        {
            var crypto = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var bytes  = new byte[5];

            crypto.GetBytes(bytes);                                          // get an array of random bytes.
            return(BitConverter.ToString(bytes).Replace("-", string.Empty)); // convert array to hex values.
        }
        public static string CreateSalt(int SaltSize)
        {
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] Salt = new byte[SaltSize];
            rng.GetBytes(Salt);
            return(Convert.ToBase64String(Salt));
        }
Example #23
0
 /// <summary>
 /// 随机数
 /// </summary>
 /// <returns></returns>
 internal int GetRandomSeed()
 {
     byte[] bytes = new byte[4];
     System.Security.Cryptography.RNGCryptoServiceProvider rng =
         new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytes);
     return(BitConverter.ToInt32(bytes, 0));
 }
Example #24
0
 public string CreateSalt()
 {
     int size = 10;//new Random().Next(10, 15);
     var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     var buff = new byte[size];
     rng.GetBytes(buff);
     return Convert.ToBase64String(buff);
 }
Example #25
0
        string RandomString(int length)
        {
            string allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
            }
            if (string.IsNullOrEmpty(allowedChars))
            {
                throw new ArgumentException("allowedChars may not be empty.");
            }

            const int byteSize       = 0x100;
            var       allowedCharSet = new HashSet <char>(allowedChars).ToArray();

            if (byteSize < allowedCharSet.Length)
            {
                throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize));
            }

            // Guid.NewGuid and System.Random are not particularly random. By using a
            // cryptographically-secure random number generator, the caller is always
            // protected, regardless of use.
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            var result = new StringBuilder();
            var buf    = new byte[128];

            while (result.Length < length)
            {
                rng.GetBytes(buf);
                for (var i = 0; i < buf.Length && result.Length < length; ++i)
                {
                    // Divide the byte into allowedCharSet-sized groups. If the
                    // random value falls into the last group and the last group is
                    // too small to choose from the entire allowedCharSet, ignore
                    // the value in order to avoid biasing the result.
                    var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);
                    if (outOfRangeStart <= buf[i])
                    {
                        continue;
                    }
                    result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
                }
            }
            SqlConnection cn = new SqlConnection(st.ConStr);

            cn.Open();
            object c = new SqlCommand("SELECT * FROM employees WHERE imgkey='" + result + "'", cn).ExecuteScalar();

            if (!DBNull.Value.Equals(c) && c != null)
            {
                cn.Close();
                return(RandomString(length));
            }
            return(result.ToString());
        }
 public static byte[] GetRandomBytes(int numberOfBytes)
 {
     using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
     {
         var bytes = new byte[numberOfBytes];
         rng.GetBytes(bytes);
         return(bytes);
     }
 }
        public string CreateSalt()
        {
            int size = 10;//new Random().Next(10, 15);
            var rng  = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buff = new byte[size];

            rng.GetBytes(buff);
            return(Convert.ToBase64String(buff));
        }
Example #28
0
        /// <summary>
        /// Return random string by specific length.
        /// </summary>
        /// <param name="length">String length.</param>
        /// <param name="NumbersOnly">Numbers only flag.</param>
        /// <returns>String with specified length.</returns>
        public static string RandomString(int length, bool NumbersOnly = false)
        {
            string allowedChars;

            if (NumbersOnly)
            {
                allowedChars = "0123456789";
            }
            else
            {
                allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            }

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
            }
            if (string.IsNullOrEmpty(allowedChars))
            {
                throw new ArgumentException("allowedChars may not be empty.");
            }

            const int byteSize       = 0x100;
            var       allowedCharSet = allowedChars.ToCharArray();

            if (byteSize < allowedCharSet.Length)
            {
                throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize));
            }

            // Guid.NewGuid and System.Random are not particularly random. By using a
            // cryptographically-secure random number generator, the caller is always
            // protected, regardless of use.
            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                var result = new StringBuilder();
                var buf    = new byte[128];
                while (result.Length < length)
                {
                    rng.GetBytes(buf);
                    for (var i = 0; i < buf.Length && result.Length < length; ++i)
                    {
                        // Divide the byte into allowedCharSet-sized groups. If the
                        // random value falls into the last group and the last group is
                        // too small to choose from the entire allowedCharSet, ignore
                        // the value in order to avoid biasing the result.
                        var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);
                        if (outOfRangeStart <= buf[i])
                        {
                            continue;
                        }
                        result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
                    }
                }
                return(result.ToString());
            }
        }
Example #29
0
        public string GenerateSalt()
        {
            //Generated a new salt to be added to the end of the password
            var rng  = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buff = new byte[15];

            rng.GetBytes(buff);
            return(Convert.ToBase64String(buff));
        }
Example #30
0
 public static int GetRand()
 {
     using (System.Security.Cryptography.RNGCryptoServiceProvider rg = new System.Security.Cryptography.RNGCryptoServiceProvider())
     {
         byte[] rno = new byte[5];
         rg.GetBytes(rno);
         return((int)BitConverter.ToUInt32(rno, 0) & 0xFFFFF);
     }
 }
Example #31
0
        public byte[] DoThing(string foo)
        {
            Console.WriteLine($"Received {foo}");
            var d    = new byte[64];
            var rand = new System.Security.Cryptography.RNGCryptoServiceProvider();

            rand.GetBytes(d);
            return(d);
        }
Example #32
0
        /*
         * public static System.Data.IDbCommand GetCommand(this IConnection connection, string commandText, System.Data.IDbTransaction t = null, System.Data.CommandType commandType = System.Data.CommandType.Text, params DataParameter[] parameter)
         * {
         *  var cmd = connection.CreateCommand();
         *  cmd.CommandType = commandType;
         *  cmd.CommandText = commandText;
         *
         *  if (null != parameter)
         *  {
         *      foreach (var item in parameter)
         *      {
         *          var p = cmd.CreateParameter();
         *          p.ParameterName = item.Name;
         *          //p.Value = System.DateTime.MinValue.Equals(item.Value) ? System.DBNull.Value : item.Value ?? System.DBNull.Value;
         *          p.Value = item.Value ?? System.DBNull.Value;
         *          cmd.Parameters.Add(p);
         *      }
         *  }
         *
         *  cmd.Transaction = t;
         *  return cmd;
         * }
         *
         * public static int ExecuteNonQuery(this IConnection connection, string commandText, System.Data.CommandType commandType = System.Data.CommandType.Text, params DataParameter[] parameter)
         * {
         *  return connection.ExecutePack(() =>
         *  {
         *      using (var cmd = connection.GetCommand(commandText, connection.Transaction, commandType, parameter))
         *      {
         *          return cmd.ExecuteNonQuery();
         *      }
         *  });
         * }
         *
         * public static Result ExecuteScalar<Result>(this IConnection connection, string commandText, System.Data.CommandType commandType = System.Data.CommandType.Text, params DataParameter[] parameter)
         * {
         *  return connection.ExecutePack(() =>
         *  {
         *      using (var cmd = connection.GetCommand(commandText, connection.Transaction, commandType, parameter))
         *      {
         *          return (Result)cmd.ExecuteScalar();
         *      }
         *  }, minusOneExcep: false);
         * }
         *
         * public static System.Collections.Generic.IList<TEntity> Execute<TEntity>(this IConnection connection, string commandText, System.Data.CommandType commandType = System.Data.CommandType.Text, params DataParameter[] parameter)
         * {
         *  return connection.ExecutePack(() =>
         *  {
         *      using (var cmd = connection.GetCommand(commandText, connection.Transaction, commandType, parameter))
         *      {
         *          using (var reader = cmd.ExecuteReader())
         *          {
         *              return reader.ToEntity<TEntity>();
         *          }
         *      }
         *  }, minusOneExcep: false);
         * }
         *
         * public static System.Collections.Generic.IList<TEntity> ToEntity<TEntity>(this System.Data.IDataReader reader) => new AutoMapper.MapperConfiguration(cfg =>
         * {
         *  AutoMapper.Data.ConfigurationExtensions.AddDataReaderMapping(cfg);
         *  cfg.CreateMap<System.Data.IDataReader, TEntity>();
         * }).CreateMapper().Map<System.Collections.Generic.IList<TEntity>>(reader);
         *
         * internal static Result ExecutePack<Result>(this IConnection connection, System.Func<Result> func, bool minusOneExcep = true)
         * {
         *  bool isCreateTransaction = false;
         *  if (null == connection.Transaction) { connection.BeginTransaction(); isCreateTransaction = !isCreateTransaction; }
         *
         *  try
         *  {
         *      var result = func();
         *
         *      if (minusOneExcep && (typeof(Result).Equals(typeof(int)) || typeof(Result).Equals(typeof(long))))
         *      {
         *          //var count = System.Convert.ToInt32(result);
         *          if (Equals(-1, result))
         *          {
         *              connection.Rollback();
         *              throw new System.Exception("Affected the number of records -1");
         *          }
         *      }
         *
         *      if (isCreateTransaction) { connection.Commit(); }
         *      return result;
         *  }
         *  catch (System.Exception ex) { if (null != connection.Transaction) { connection.Rollback(); } throw ex; }
         *  finally { if (isCreateTransaction && null != connection.Transaction) { connection.Transaction.Dispose(); } }
         * }
         */

        static int Random(int maxValue)
        {
            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                var bytes = new byte[4];
                rng.GetBytes(bytes);
                return(new System.Random(System.BitConverter.ToInt32(bytes, 0)).Next(maxValue));
            }
        }
Example #33
0
        /// <summary>
        /// 获取随机数
        /// </summary>
        /// <returns></returns>
        private static string GetNum()
        {
            byte[] bytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            int result = (BitConverter.ToInt32(bytes, 0) % 10);

            return(Math.Abs(result).ToString());
        }
Example #34
0
 /// <summary>
 /// 获得一串随机的字节
 /// </summary>
 /// <returns></returns>
 private static byte[] GetRandomBytes(int num)
 {
     byte[] bytes = new byte[num];
     using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
     {
         rng.GetBytes(bytes);
         return(bytes);
     }
 }
Example #35
0
        /// <summary>
        /// Creates a salted PBKDF2 hash of the password.
        /// </summary>
        /// <param name="password">The password to hash.</param>
        /// <returns>The hash of the password.</returns>
        public static string CreateHash(string password)
        {
            var csprng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] salt = new byte[24];
            csprng.GetBytes(salt);
            byte[] hash = PBKDF2(password, salt, 1000, 24);
            return(1000 + ":" + Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(hash));
        }
Example #36
0
        public static int Random(this int maxValue, System.Security.Cryptography.RNGCryptoServiceProvider rng = null)
        {
            rng = rng ?? new System.Security.Cryptography.RNGCryptoServiceProvider();
            decimal _base = (decimal)long.MaxValue;

            byte[] rndSeries = new byte[8];
            rng.GetBytes(rndSeries);
            return((int)(Math.Abs(BitConverter.ToInt64(rndSeries, 0)) / _base * maxValue));
        }
Example #37
0
        public static byte[] GetRandomBytes(int length)
        {
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buffer = new byte[length];

            rng.GetBytes(buffer);

            return buffer;
        }
Example #38
0
        public static string CreateNewSecret(int secretLengthInBits)
        {
            byte[] buf = new byte[secretLengthInBits / 8];

            System.Security.Cryptography.RNGCryptoServiceProvider rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rnd.GetBytes(buf);

            return(Base32Encoding.ToString(buf));
        }
Example #39
0
        /// <summary>
        /// 使用RNGCryptoServiceProvider生成种子
        /// </summary>
        /// <returns></returns>
        public int GetRandomSeed()
        {
            Random rd = new Random();

            byte[] bytes = new byte[rd.Next(0, 10000000)];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return(BitConverter.ToInt32(bytes, 0));
        }
Example #40
0
        int GetRandomSeed(string factor)
        {
            byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(factor);

            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);

            return(BitConverter.ToInt32(bytes, 0));
        }
Example #41
0
        /// <summary>
        /// You are using ZContext.Current!
        /// </summary>
        public ZActor(ZAction0 action, params object[] args)
            : this(default(string), action, args)
        {
            var rnd0 = new byte[8];
            var rng  = new System.Security.Cryptography.RNGCryptoServiceProvider();

            rng.GetNonZeroBytes(rnd0);
            this.Endpoint = string.Format("inproc://{0}", ZContext.Encoding.GetString(rnd0));
        }
Example #42
0
 public static int GetRandomNumber(int min, int max)
 {
     System.Security.Cryptography.RNGCryptoServiceProvider rng =
         new System.Security.Cryptography.RNGCryptoServiceProvider();
     byte[] buffer = new byte[4];
     rng.GetBytes(buffer);
     int result = BitConverter.ToInt32(buffer, 0);
     return new System.Random(result).Next(min, max);
 }
Example #43
0
        public void TestKeyToStringGeneration()
        {
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            var key = rng.Create256BitLowerCaseHexKey();

            Assert.AreEqual(64, key.Length);
            Assert.That(isOnlyLowercaseHexChars(key));
        }
 /// <summary>
 /// Method to generate GetCryptoRandom
 /// </summary>
 /// <returns></returns>
 private static int GetCryptoRandom()
 {
     using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
     {
         byte[] bytes = new byte[4];
         rng.GetBytes(bytes);
         return(BitConverter.ToInt32(bytes, 0));
     }
 }
Example #45
0
        private static string CreateSalt(int size)
        {
            // random provider
            var rng    = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buffer = new byte[size];

            rng.GetBytes(buffer);
            return(Convert.ToBase64String(buffer));
        }
Example #46
0
        /// <summary>
        /// Initialize the class
        /// </summary>
        public SecureDelete()
        {
            // get random buffer
            using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
                rng.GetBytes(_rndBuffer);

            // create reverse random buffer
            Buffer.BlockCopy(_rndBuffer, 0, _revBuffer, 0, _revBuffer.Length);
            Array.Reverse(_revBuffer);
        }
Example #47
0
 /// <summary>
 /// 获取线程级随机数
 /// </summary>
 /// <returns></returns>
 public static Random Random()
 {
     var bytes = new byte[4];
     var rng =
         new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytes);
     var seed = BitConverter.ToInt32(bytes, 0);
     var tick = DateTime.Now.Ticks + (seed);
     return new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
 }
Example #48
0
        public Customer(string name, int customerId, ModuleEnum[] modules)
        {
            Name = name;
            CustomerId = customerId;
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            Random r = new Random(rng.GetHashCode());

            SatisfactionLevel = r.NextDouble() * 10;
            Modules = modules;
        }
Example #49
0
 public static System.String GetRandomString(System.Int32 length)
 {
     System.Byte[] seedBuffer = new System.Byte[4];
     using (var rngCryptoServiceProvider = new System.Security.Cryptography.RNGCryptoServiceProvider())
     {
         rngCryptoServiceProvider.GetBytes(seedBuffer);
         System.String chars = "-abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         System.Random random = new System.Random(System.BitConverter.ToInt32(seedBuffer, 0));
         return new System.String(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
     }
 }
Example #50
0
        public static string createRandomString()
        {
            //create Random Number Generator
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            //create random string
            byte[] randomBytes = new byte[32];
            rng.GetBytes (randomBytes);

            return byteArrayToHexString (randomBytes);
        }
Example #51
0
        protected static System.Security.Cryptography.RNGCryptoServiceProvider rnd;//om de auto's een willekeurige kant op te laten gaan

        public Simulation(SimControl simControl)
        {
            rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();
            this.simControl = simControl;
            this.simStarted = false;
            spawnerList = new List<Spawner>();
            waitingCars = 0;
            simSleep = 70;
            extraSpeed = 0;
            efficiencyNumbers = new List<string[]>();
            
        }
Example #52
0
        public static int secRand()
        {
            byte[] randByte = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider secRand = new System.Security.Cryptography.RNGCryptoServiceProvider();
            secRand.GetBytes(randByte);
            int seed = ((randByte[0] & 0x7f) << 24 |
                randByte[1] << 16 |
                randByte[2] << 8 |
                randByte[3]);

            return seed;
        }
Example #53
0
        public static string GeneratePassword(int intLength, int intNumberOfNonAlphaNumericCharacters)
        {
            int intNonAlphaCount = 0;
            byte[] buffer = new byte[intLength];
            char[] aryPassword = new char[intLength];
            char[] aryPunctuations = "!@@$%$%*()@-+=[{]}#%>|%#?".ToCharArray();

            System.Security.Cryptography.RNGCryptoServiceProvider objCrypto = new System.Security.Cryptography.RNGCryptoServiceProvider();
            objCrypto.GetBytes(buffer);

            for (int i = 0; i < intLength; i++)
            {
                //Convert each byte into its representative character
                int intRndChr = (buffer[i] % 87);
                if (intRndChr < 10)
                    aryPassword[i] = Convert.ToChar(Convert.ToUInt16(48 + intRndChr));
                else if (intRndChr < 36)
                    aryPassword[i] = Convert.ToChar(Convert.ToUInt16((65 + intRndChr) - 10));
                else if (intRndChr < 62)
                    aryPassword[i] = Convert.ToChar(Convert.ToUInt16((97 + intRndChr) - 36));
                else
                {
                    if (intNonAlphaCount >= intNumberOfNonAlphaNumericCharacters)
                    {
                        i--;
                        objCrypto.GetBytes(buffer);
                    }
                    else
                    {
                        aryPassword[i] = aryPunctuations[intRndChr - 62];
                        intNonAlphaCount++;
                    }
                }
            }

            if (intNonAlphaCount < intNumberOfNonAlphaNumericCharacters)
            {
                Random objRandom = new Random();
                for (int i = 0; i < (intNumberOfNonAlphaNumericCharacters - intNonAlphaCount); i++)
                {
                    int intIndex;
                    do
                    {
                        intIndex = objRandom.Next(0, intLength);
                    } while (!Char.IsLetterOrDigit(aryPassword[intIndex]));
                    aryPassword[intIndex] = aryPunctuations[objRandom.Next(0, aryPunctuations.Length)];
                }
            }

            Array.Reverse(aryPassword);
            return new string(aryPassword);
        }
Example #54
0
 public Challenge(string CBCryptHostId)
 {
     this.CBCryptHostId = CBCryptHostId;
     this.ChallengeBytes = new byte[ChallengeSize];
     // The easiest way for me to generate an ephemeral key is to feed random bytes into CBCrypt.GenerateKeyPair
     var tempKey = new byte[tempKeySize];
     using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) {
         rng.GetBytes(this.ChallengeBytes);
         rng.GetBytes(tempKey);
     }
     this.ServerEphemeralKey = new CBCryptKey(tempKey);
     this.ServerPublicKeyDerEncoded = this.ServerEphemeralKey.GetPublicKeyDerEncoded();
 }
Example #55
0
        /// <summary>
        /// Constructor used by fork, based on the constructor in Tile
        /// here all default values of the Spawner are set.
        /// </summary>
        /// <param name="sim"></param>
        /// <param name="direction"></param>
        public Spawner(SimControl sim, int direction)
        {
            this.name = "Spawner";
            carsSpawnChance = 3;
            spawnLane = 0;
            this.lanesIn = 1;
            this.lanesOut = 1;
            this.spawnPerTick = 0.05;
            directions.Add(direction);
            currentSpawn = 1;
            rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();


        }
        public string createHashedPassword(string pwd)
        {
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
                byte[] salt = new byte[8];
                rng.GetBytes(salt); // Create an 8 byte salt
                var iterations = 1000; // Choose a value that will perform well given your hardware.
                var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(pwd, salt, iterations);
                var hash = pbkdf2.GetBytes(60); // Get 60 bytes for the hash

                var str = System.Text.Encoding.Default.GetString(hash);

                Console.WriteLine(str);

                return hash.ToString();
        }
Example #57
0
        static String BuildAuthenticationHeader()
        {
            System.Security.Cryptography.RNGCryptoServiceProvider provider = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] bytes = new byte[20];
            provider.GetBytes(bytes);
            String nonce = System.Convert.ToBase64String(bytes);
            String created = String.Format("{0:yyyy-MM-dd'T'HH:mm:sszz00}", DateTime.Now);
            byte[] intermediateBytes = System.Text.UTF8Encoding.UTF8.GetBytes(nonce + created + apiKey);
            byte[] passwordDigestHash = System.Security.Cryptography.SHA256.Create().ComputeHash(intermediateBytes);

            String passwordDigest = System.Convert.ToBase64String(passwordDigestHash, Base64FormattingOptions.None);

            return "UsernameToken Username=\"" + apiUsername + "\",PasswordDigest=\"" + passwordDigest + "\",Nonce=\"" + nonce + "\",Created=\"" + created + "\"";
        }
        public static string ToHashString(this byte [] bytes, bool numeric = false)
        {
            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                rng.GetBytes(bytes);
                if (numeric)
                {
                    bytes.UpdateEach((b) => (byte)(byteMod(b, 0xA) + OFFSET));
                    return System.Text.Encoding.UTF8.GetString(bytes);
                }

                bytes.UpdateEach((b) => (byte)(byteMod(b, MOD) + OFFSET));
                bytes.UpdateEach((b) => (byte)((b > BREAK) ? b + ALPHA_OFFSET : b));
                return System.Text.Encoding.UTF8.GetString(bytes);
            }
        }
Example #59
0
        public Vehicle(Point pos, Point dest, int len, int speed, int direction, int lane)
        {
            updatePoint = 0;
            position = pos;
            destination = dest;
            //size = new Size(10, len);
            this.speed = speed;
            this.direction = direction;
            nextDirection = direction;
            this.lane = lane;
            this.oldLane = lane;
            lastDirection = direction;

            rotated = false;
            rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();
        }
Example #60
0
        /// <summary>
        /// 参考:msdn上的RNGCryptoServiceProvider例子
        /// </summary>
        /// <param name="numSeeds"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private static int NextRandom(int numSeeds, int length)
        {
            // Create a byte array to hold the random value.
            byte[] randomNumber = new byte[length];
            // Create a new instance of the RNGCryptoServiceProvider.
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            // Fill the array with a random value.
            rng.GetBytes(randomNumber);
            // Convert the byte to an uint value to make the modulus operation easier.
            uint randomResult = 0x0;
            for (int i = 0; i < length; i++)
            {
                randomResult |= ((uint)randomNumber[i] << ((length - 1 - i) * 8));
            }

            return (int)(randomResult % numSeeds) + 1;
        }