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); }
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(); } }
/// <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(); } }
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(); }
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); } } }
/// <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); }
/// <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)); }
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"); }
static string GetNonceAsHexDigitString(int lengthInBytes) { var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); var bytes = new byte[lengthInBytes]; rng.GetBytes(bytes); return ToHexDigitString(bytes); }
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)); }
/// <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)); }
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)); }
public Noise(int size, float Amp) { BuffSize = size; Amplitude = Amp; NoiseGen = new System.Security.Cryptography.RNGCryptoServiceProvider(); RandomNoiseBytes = new byte[size]; Result = new float[size]; }
private static byte[] GenerateRandomBytes(int count) { var b = new byte[count]; var c = new System.Security.Cryptography.RNGCryptoServiceProvider(); c.GetNonZeroBytes(b); return(b); }
protected string CreateSalt(int size) { var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); var buff = new byte[size]; rng.GetBytes(buff); return Convert.ToBase64String(buff); }
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)); }
public string CreateSalt(int size) { var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); var buff = new byte[size]; rng.GetBytes(buff); return(Convert.ToBase64String(buff)); }
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)); }
/// <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)); }
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); }
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)); }
/// <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()); } }
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)); }
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); } }
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); }
/* * 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)); } }
/// <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()); }
/// <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); } }
/// <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)); }
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)); }
public static byte[] GetRandomBytes(int length) { var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); var buffer = new byte[length]; rng.GetBytes(buffer); return buffer; }
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)); }
/// <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)); }
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)); }
/// <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)); }
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); }
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)); } }
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)); }
/// <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); }
/// <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)); }
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; }
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()); } }
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); }
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[]>(); }
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; }
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); }
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(); }
/// <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(); }
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); } }
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(); }
/// <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; }