private void CompareBlocks(int BlockSize) { using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) { byte[] key = new byte[32]; byte[] iv = new byte[BlockSize]; byte[] data = new byte[1600]; rng.GetBytes(key); rng.GetBytes(iv); rng.GetBytes(data); byte[] enc1 = EncryptRDX(key, iv, data); byte[] enc2 = EncryptManaged(key, iv, data); if (Compare.AreEqual(enc1, enc2) == false) throw new Exception("Encrypted output is not equal!"); byte[] dec1 = DecryptRDX(key, iv, data); byte[] dec2 = DecryptManaged(key, iv, data); if (Compare.AreEqual(dec2, dec1) == false) throw new Exception("Decrypted output is not equal to input data!"); } }
/// <summary> /// CBC mode speed comparisons between RijndaelManaged and RDX /// </summary> /// <param name="Iterations">Number of times to perform this test</param> /// <param name="BlockCount">Number of 16 byte blocks to encrypt</param> /// <returns>Elapsed milliseconds [string]</returns> public string Test() { byte[] key = new byte[32]; byte[] iv = new byte[16]; byte[] data = new byte[this.BlockCount * 16]; string ft = @"m\:ss\.ff"; Stopwatch runTimer = new Stopwatch(); using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) { rng.GetBytes(key); rng.GetBytes(iv); rng.GetBytes(data); } runTimer.Start(); for (int i = 0; i < this.Iterations; i++) PerformTest(key, iv, data); runTimer.Stop(); TimeSpan t1 = TimeSpan.FromMilliseconds(runTimer.Elapsed.TotalMilliseconds); return t1.ToString(ft); }
/// <summary> /// /// </summary> public ConsoleListener() { using (var numberGen = new RNGCryptoServiceProvider()) { var data = new byte[20]; var data2 = new byte[20]; numberGen.GetBytes(data); numberGen.GetBytes(data2); using(MD5 md5 = new MD5CryptoServiceProvider()) { string str = ServerSettings.Salt2 + Convert.ToBase64String(data) + Convert.ToBase64String(data2) + ServerSettings.Salt; byte[] buffer = new byte[str.Length * 2]; Encoding.Unicode.GetEncoder().GetBytes(str.ToCharArray(), 0, str.Length, buffer, 0, true); byte[] result = md5.ComputeHash(buffer); StringBuilder sb = new StringBuilder(); for (int i = 0; i < result.Length; i++) sb.Append(result[i].ToString("X2")); this.XID = sb.ToString(); } } }
public string Test() { byte[] key = new byte[32]; byte[] iv = new byte[8]; byte[] data = new byte[BlockCount * 64]; string ft = @"m\:ss\.ff"; Stopwatch runTimer = new Stopwatch(); using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) { rng.GetBytes(key); rng.GetBytes(iv); rng.GetBytes(data); } runTimer.Start(); if (this.Implementation == SalsaImplementations.Ver1) { for (int i = 0; i < Iterations; i++) Salsa1Test(key, iv, data); } else { for (int i = 0; i < Iterations; i++) Salsa2Test(key, iv, data); } runTimer.Stop(); TimeSpan t1 = TimeSpan.FromMilliseconds(runTimer.Elapsed.TotalMilliseconds); return t1.ToString(ft); }
public static string GetRandomString(int length) { //returns random string of length specified with characters including: 0-9, a-z, A-Z char[] ca = new char[length]; byte[] random = new Byte[length]; //RNGCryptoServiceProvider is an implementation of a random number generator. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(random); // The array is now filled with cryptographically strong random bytes. for (int i = 0; i < length; i++) { bool found = false; int rand = (int)random[i]; while (!found) { if (((rand >= 48) && (rand <= 57)) || ((rand >= 65) && (rand <= 90)) || ((rand >= 97) && (rand <= 122))) { found = true; } else { //get a new random int. byte[] single = new byte[1]; rng.GetBytes(single); rand = single[0]; } } char ci = (char)rand; ca[i] = ci; } string s = new string(ca); return s; }
bool testRng(Session session) { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(session); byte[] data1 = new byte[1024]; byte[] data2 = new byte[1024]; byte[] data3 = new byte[1024]; rng.GetBytes(data1); rng.GetBytes(data2); rng.Dispose(); rng = new RNGCryptoServiceProvider(session); rng.GetBytes(data3); rng.Dispose(); int same = 0; for (int i = 0; i < data1.Length; i++) { if (data1[i] == data2[i] || data1[i] == data3[i] || data2[i] == data3[i]) same++; } return same < 32; // ~3% matching elements }
public void Send(double mouseX,double mouseY) { cid = getCID(); sid = getSID(); var callerID = sid; Random rnd = new Random(DateTime.Now.Millisecond); RNGCryptoServiceProvider rngc = new RNGCryptoServiceProvider(); byte[] bta = new byte[1]; rngc.GetBytes(bta); int _signal = bta[0] % 25; //0~24 if (_signal < 5) //5/25垂直或水平座標線 signal = 0; if (_signal ==5||_signal==6) //2/25聲納探測 signal = 1; if (_signal >6 && _signal<=10) //4/25隨機數字+引線 signal = 2; if (_signal ==11) //1/25 gooleTTS!! signal = 3; if (_signal > 11&&_signal<=16) //5/25 移動座標線 signal = 4; if (_signal > 16 &&_signal <= 19) //3/25 虛線 signal = 5; if (_signal > 19 && _signal <= 21) //2/25 資料傳送 signal = 6; if (_signal > 21 && _signal <= 24) //3/25 Glich signal = 7; bool b =rnd.Next(2)==1?true:false; Color col = Color.FromArgb(rnd.Next(90), rnd.Next(90)+50, rnd.Next(90)+160); string rndColor = ColorTranslator.ToHtml(col); string[] usercolors = { "#6dffff", "#FFB6FF", "#FFFA64", "#7BFFB9", "#AA6BFF" }; string userColor = usercolors[Math.Abs(sid.GetHashCode() % 5)]; rngc.GetBytes(bta); double r1 = (double)bta[0] / 256.0; rngc.GetBytes(bta); double r2 = (double)bta[0] / 256.0; string words = ""; if (signal == 3) //其他不需要 { for (int i = 0; i < (r1 * 4 + 2); i++) { rngc.GetBytes(bta); int sRnd = (Int32)bta[0]; for (int j = 0; j < sRnd; j++) rnd.Next(); words += Global.dictionary[rnd.Next(Global.dictionary.Count)] + " "; if (words.Length > 30) break; } } if (signal == 7) Clients.Caller.broadcast(mouseX, mouseY, signal, b, rndColor, r1, r2, words, callerID, userColor); else { Clients.All.broadcast(mouseX, mouseY, signal, b, rndColor, r1, r2, words, callerID, userColor); Clients.All.osc(new object[] { mouseX, mouseY, signal, b, rndColor, r1, r2, words, callerID, userColor }); } }
static MachineKeyConfig () { autogenerated = new byte [64]; RNGCryptoServiceProvider cp = new RNGCryptoServiceProvider (); cp.GetBytes (autogenerated); autogenerated_decrypt = new byte [64]; cp.GetBytes (autogenerated_decrypt); }
/// <summary> /// Generate a new key and IV. /// </summary> /// <param name="encoding"></param> public AES(Encoding encoding) { this.mode = new SicBlockCipher(new AesFastEngine()); RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider(); // Generate random key and IV rngCsp.GetBytes(key); rngCsp.GetBytes(iv); this.encoding = encoding; }
/// <summary> /// Creates a pseudo-random password containing the number of character classes /// defined by complexity, where 2 = alpha, 3 = alpha+num, 4 = alpha+num+special. /// </summary> public static string GeneratePassword(int length, int complexity) { System.Security.Cryptography.RNGCryptoServiceProvider csp = new System.Security.Cryptography.RNGCryptoServiceProvider(); // Define the possible character classes where complexity defines the number // of classes to include in the final output. char[][] classes = { @"abcdefghijklmnopqrstuvwxyz".ToCharArray(), @"ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(), @"0123456789".ToCharArray(), @" !""#$%&'()*+,./:;<>?@[\]^_{|}~".ToCharArray(), }; complexity = Math.Max(1, Math.Min(classes.Length, complexity)); if (length < complexity) throw new ArgumentOutOfRangeException("length"); // Since we are taking a random number 0-255 and modulo that by the number of // characters, characters that appear earilier in this array will recieve a // heavier weight. To counter this we will then reorder the array randomly. // This should prevent any specific character class from recieving a priority // based on it's order. char[] allchars = classes.Take(complexity).SelectMany(c => c).ToArray(); byte[] bytes = new byte[allchars.Length]; csp.GetBytes(bytes); for (int i = 0; i < allchars.Length; i++) { char tmp = allchars[i]; allchars[i] = allchars[bytes[i] % allchars.Length]; allchars[bytes[i] % allchars.Length] = tmp; } // Create the random values to select the characters Array.Resize(ref bytes, length); char[] result = new char[length]; while (true) { csp.GetBytes(bytes); // Obtain the character of the class for each random byte for (int i = 0; i < length; i++) result[i] = allchars[bytes[i] % allchars.Length]; // Verify that it does not start or end with whitespace if (Char.IsWhiteSpace(result[0]) || Char.IsWhiteSpace(result[(length - 1) % length])) continue; string testResult = new string(result); // Verify that all character classes are represented if (0 != classes.Take(complexity).Count(c => testResult.IndexOfAny(c) < 0)) continue; return testResult; } }
void GenerateAes() { var rng = new RNGCryptoServiceProvider(); Globals.AesKey = new byte[16]; Globals.AesIV = new byte[16]; rng.GetBytes(Globals.AesKey); rng.GetBytes(Globals.AesIV); }
/// <summary> /// Creates AES instance /// </summary> public AesEncryptor() { aes = Aes.Create(); using (var rng = new RNGCryptoServiceProvider()) { rng.GetBytes(key); rng.GetBytes(iVec); } aes.IV = iVec; aes.Key = key; aes.Padding = PaddingMode.Zeros; }
private static int GetRandomSeed() { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); return(System.BitConverter.ToInt32(bytes, 0)); }
static public 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)); }
static void Main(string[] arges) { string n = "1"; while (n == "1") { // Random ran = new Random(Guid().NewGuid().GetHashCode()); double areasummary = 0; int i = 0; while (i < 10) { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); int t = BitConverter.ToInt32(bytes, 0); Random ran = new Random(t);//网上查到的解决伪随机的方案,经测试可行 int kind = ran.Next() % 3; Shape thisshape = ShapeFactory.Produce(kind, ran.Next(0, 10), ran.Next(0, 10), ran.Next(0, 10)); if (thisshape.Islegal()) { areasummary += thisshape.Area; i += 1; } } Console.WriteLine($"这10个图形的面积之和为{areasummary}"); Console.WriteLine("输入0结束,输入1再来一次:"); n = Console.ReadLine(); } }
public byte[] GenerateSalt() { var rng = new RNGCryptoServiceProvider(); var salt = new byte[256]; rng.GetBytes(salt); return salt; }
/// <summary> /// Creates an array of bytes with a cryptographically strong sequence of random values. /// </summary> /// <param name="length">Length of array to create.</param> /// <returns>An array of bytes filled with a cryptographically strong sequence of random values.</returns> public static byte[] GetRandomBytes(int length) { byte[] randomBytes = new byte[length]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(randomBytes); return randomBytes; }
public static byte[] generateSalt() { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] salt = new byte[256]; rng.GetBytes(salt); return salt; }
public static byte[] CreateSalt(int size = 16) { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[size]; rng.GetBytes(buff); return buff; }
public static Int64 NextInt64() { var bytes = new byte[sizeof(Int64)]; RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider(); Gen.GetBytes(bytes); return BitConverter.ToInt64(bytes , 0); }
/// <summary> /// Returns the given number of seed bytes generated for the first running of a new instance /// of the random number generator. /// </summary> /// <param name="numberOfBytes">Number of seed bytes to generate.</param> /// <returns>Seed bytes generated</returns> public static byte[] GetSeed(int numberOfBytes) { RNGCryptoServiceProvider generatedSeed = new RNGCryptoServiceProvider(); byte[] seeds = new byte[numberOfBytes]; generatedSeed.GetBytes(seeds); return seeds; }
/// <summary> /// Creates a key based on the indicated size. /// </summary> /// <param name="numBytes">size of the key.</param> /// <returns>Generated key of the specified length.</returns> public static string CreateKey(int numBytes) { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[numBytes]; rng.GetBytes(buff); return BytesToHexString(buff); }
public static byte[] GetBuffer(int length) { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] output = new byte[length]; rng.GetBytes(output); return output; }
public static string Generate(int length, string 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 = 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. using (var rng = new 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 CreateReference(int size) { const int byteSize = 0x100; var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray(); var allowedCharSet = new HashSet<char>(chars).ToArray(); using (var cryptoProvider = new RNGCryptoServiceProvider()) { var result = new StringBuilder(); var buffer = new byte[128]; while (result.Length < size) { cryptoProvider.GetBytes(buffer); for (var i = 0; i < buffer.Length && result.Length < size; ++i) { var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length); if (outOfRangeStart <= buffer[i]) { continue; } result.Append(allowedCharSet[buffer[i] % allowedCharSet.Length]); } } return result.ToString(); } }
public static string GenerateSalt(int saltSize) { RNGCryptoServiceProvider rngCryptoServiceProvider = new RNGCryptoServiceProvider(); byte[] byteArray = new Byte[saltSize]; rngCryptoServiceProvider.GetBytes(byteArray); return Convert.ToBase64String(byteArray); }
/// <summary> /// CreateHashedText /// </summary> /// <param name="plainText"></param> /// <param name="useSalt"></param> /// <returns></returns> public static KeyValuePair<string, string> CreateHashedText(string plainText,bool useSalt) { var plainTextBytes = Encoding.Unicode.GetBytes(plainText); string salt = string.Empty; string hashedText = string.Empty; if (useSalt) { var saltBytes = new byte[0x10]; using (var random = new RNGCryptoServiceProvider()) { random.GetBytes(saltBytes); } salt = Convert.ToBase64String(saltBytes); plainTextBytes=saltBytes.Concat(plainTextBytes).ToArray(); } byte[] hashBytes; using (var hashAlgorithm = HashAlgorithm.Create()) { hashBytes = hashAlgorithm.ComputeHash(plainTextBytes); } hashedText = Convert.ToBase64String(hashBytes); return new KeyValuePair<string, string>(hashedText, salt); }
public string GenerateSalt() { var random = new RNGCryptoServiceProvider(); var salt = new Byte[8]; random.GetBytes(salt); return Convert.ToBase64String(salt); }
public static int NextInt32(int max) { byte[] bytes = new byte[sizeof(int)]; RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider(); Gen.GetBytes(bytes); return Math.Abs(BitConverter.ToInt32(bytes, 0) % max); }
public string GenerateSalt() { var data = new byte[0x10]; using (var cryptoServiceProvider = new RNGCryptoServiceProvider()) { cryptoServiceProvider.GetBytes(data); return Convert.ToBase64String(data); } }
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); }
/// <summary> /// Generate Password Salt Int to add to password /// </summary> /// <returns>Salt Int</returns> internal string GenerateSalt() { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[32]; rng.GetBytes(buff); return Convert.ToBase64String(buff); }
public static Stack<int> CreateCardsValues([NotNull] GameStage stage) { Contract.Requires(stage != null); var totalNumberOfCards = stage.CardsRows.Sum(); var numberOfDifferentCards = totalNumberOfCards / stage.CardsInGroup; var cardsValues = new List<int>(); for (int i = 0; i < numberOfDifferentCards; i++) { cardsValues.AddRange(Enumerable.Repeat(i, stage.CardsInGroup)); } using (var rndGen = new RNGCryptoServiceProvider()) { byte[] bytes = new byte[cardsValues.Count]; rndGen.GetBytes(bytes); int[] ints = bytes.Select(b => b - byte.MaxValue / 2).ToArray(); var rnd = new Random((int)DateTime.UtcNow.Ticks); cardsValues.Sort((c1, c2) => ints[rnd.Next(0, ints.Length)]); } return new Stack<int>(cardsValues); }
public string CreateSalt(int SaltSize) { var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); byte[] Salt = new byte[SaltSize]; rng.GetBytes(Salt); return(Convert.ToBase64String(Salt)); }
//generate salt method 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 byte[] generateIV() { using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) { byte[] nonce = new byte[16]; rng.GetBytes(nonce); return(nonce); } }
/// <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()); } }
private static Random GetRandom() { //产生随机数 参考代码:https://www.cnblogs.com/xiaowie/p/8759837.html byte[] randomBytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rngServiceProivider = new System.Security.Cryptography.RNGCryptoServiceProvider(); rngServiceProivider.GetBytes(randomBytes); int iSeed = BitConverter.ToInt32(randomBytes, 0); return(new Random(iSeed)); }
public static string CreateSalt() { Random rand = new Random(); int random_number = rand.Next(0, 100); var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); var buff = new byte[random_number]; rng.GetBytes(buff); return(Convert.ToBase64String(buff)); }
private static int SecureInt() { if (provider == null) { provider = new System.Security.Cryptography.RNGCryptoServiceProvider(); } var byteArray = new byte[4]; provider.GetBytes(byteArray); //convert 4 bytes to an integer return(BitConverter.ToInt32(byteArray, 0)); }
private static int Next(int numSeeds, int length) { byte[] buffer = new byte[length]; System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider(); Gen.GetBytes(buffer); uint randomResult = 0x0;//这里用uint作为生成的随机数 for (int i = 0; i < length; i++) { randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8)); } return((int)(randomResult % numSeeds)); }
public ulong GetRandomULONG() { byte[] bytes = new byte[8]; crypto_rnd.GetBytes(bytes); ulong result = 0; for (int i = 0; i < 8; i++) { int offset = 64 - 8 * (i + 1); result = result | (((ulong)bytes[i]) << offset); } return(result); }
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 = "^@*&+%$#!.;-"; // Characters allowed to be rocks. 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())); } // I cannot really explain how this works. I got it from the Internet and it gets the job done. // It generates a random string from a character set. }
/// <summary> /// Create a new randomized cipher on each startup /// </summary> private static void InitializeCipherKey() { lock (mutex) { if (key == null) { key = new byte[32]; var cr = new System.Security.Cryptography.RNGCryptoServiceProvider(); cr.GetBytes(key, 0, key.Length); } } }
/// <summary> /// 产生0~1 /// </summary> /// <returns></returns> static public double RandDouble() { //int seed = (int)System.DateTime.Now.ToBinary(); //return (float)(low + new System.Random(seed).NextDouble() * (upper - low)); decimal _base = (decimal)long.MaxValue; byte[] rndSeries = new byte[8]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(rndSeries); //不含100需去掉+1 return((double)(Math.Abs(BitConverter.ToInt64(rndSeries, 0)) / _base)); }
/// <summary> /// Creates a new and initialized instance of the TripleSec RNG (no parameters). /// </summary> public RNGV3() { // sure, the .NET RNG is pretty good, but lets make an attacker's life miserable // and also guard against a compromised RNG SSC.RNGCryptoServiceProvider rng = new SSC.RNGCryptoServiceProvider(); byte[] tempKey = new byte[512]; byte[] tempSalt = new byte[512]; rng.GetBytes(tempKey); rng.GetBytes(tempSalt); byte[] interim = new SSC.Rfc2898DeriveBytes(tempKey, tempSalt, 64).GetBytes(1024); rng.GetBytes(tempSalt); byte[] final = new SSC.Rfc2898DeriveBytes(interim, tempSalt, 64).GetBytes(72); _salt = new byte[16]; _aesIV = new byte[16]; _twofishIV = new byte[16]; _xsalsa20IV = new byte[24]; Buffer.BlockCopy(final, 0, _salt, 0, _salt.Length); Buffer.BlockCopy(final, 16, _aesIV, 0, _aesIV.Length); Buffer.BlockCopy(final, 16 + 16, _twofishIV, 0, _twofishIV.Length); Buffer.BlockCopy(final, 16 + 16 + 16, _xsalsa20IV, 0, _xsalsa20IV.Length); _ready = true; }
static IEnumerable <int> GetRandomNumbers(int size) { byte[] data = new byte[4]; using (RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(data)) { for (int i = 0; i < size; i++) { rng.GetBytes(data); int value = BitConverter.ToInt32(data, 0); yield return(value < 0 ? value * -1 : value); } } }
private void SetEncPassword(ref User user) { var salt = new Byte[32]; using (var provider = new System.Security.Cryptography.RNGCryptoServiceProvider()) { provider.GetBytes(salt); // Generated salt } var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(user.Password, salt); pbkdf2.IterationCount = 1000; byte[] hash = pbkdf2.GetBytes(32); // Hashed and salted password user.Salt = salt; user.EncPassword = hash; }
public String cas(String id, String u, String p, String c) { try { string recuperatedData = ""; //Create Connection SqlConnection conn = new SqlConnection(@"Data Source=DRACARYS\SQLEXPRESS;Initial Catalog=test;Integrated Security=SSPI"); //SQL Command SqlCommand cmd = new SqlCommand("SELECT pass FROM dbo.datalog WHERE name = '" + u + "'AND studentid = '" + id + "'AND college = '" + c + "'", conn); //Open connection conn.Open(); //To read from SQL Server SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { recuperatedData = dr["pass"].ToString(); } //Close Connections dr.Close(); conn.Close(); if (recuperatedData == p) { using (System.Security.Cryptography.RNGCryptoServiceProvider rg = new System.Security.Cryptography.RNGCryptoServiceProvider()) { byte[] rno = new byte[5]; rg.GetBytes(rno); int randomvalue = BitConverter.ToInt32(rno, 0); string s = "" + randomvalue; return(s); } } else { return("Access Denied"); } } catch (SqlException e) { return("Invalid REquest" + e); } }
/// <summary> /// 生成真随机种子 /// </summary> /// <returns></returns> public static int GetRandomSeed() { #if NETCOREAPP1_0 || NETSTANDARD1_6 using (var rdm = RandomNumberGenerator.Create()) { byte[] bytes = new byte[4]; rdm.GetBytes(bytes); return(BitConverter.ToInt32(bytes, 0)); } #else byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); return(BitConverter.ToInt32(bytes, 0)); #endif }
static public void setup() { System.Security.Cryptography.RNGCryptoServiceProvider rng; rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); byte[] randSeed = new byte[4]; rng.GetBytes(randSeed); rng.Dispose(); PRNG.seed = 0; foreach (byte b in randSeed) { PRNG.seed = (PRNG.seed << 8) | (0xff & (uint)b); } }
/// <summary> /// 随机数 /// </summary> /// <param name="j">随机数长度</param> /// <returns></returns> public static string GetSJS(int j) { string ret = ""; int intby = 0; for (int i = 0; i < j; i++) { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); intby = BitConverter.ToInt32(bytes, 0); Random ran = new Random(intby); ret += ran.Next(10); } return(ret); }
private void CompareBlocks(ShaAlg Algorithm) { if (Algorithm == ShaAlg.SHA256) { byte[] buffer = new byte[639]; byte[] hash1 = new byte[32]; byte[] hash2 = new byte[32]; using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetBytes(buffer); // SHA256 // // test digest using (VTDev.Projects.CEX.Crypto.Digests.SHA256Digest sha1 = new VTDev.Projects.CEX.Crypto.Digests.SHA256Digest()) hash1 = sha1.ComputeHash(buffer); using (System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256Managed.Create()) hash2 = sha.ComputeHash(buffer); if (!Compare.AreEqual(hash1, hash2)) { throw new Exception("SHA512 hash is not equal!"); } } else { // SHA512 // byte[] hash1 = new byte[64]; byte[] hash2 = new byte[64]; byte[] buffer = new byte[377]; using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetBytes(buffer); // test digest using (VTDev.Projects.CEX.Crypto.Digests.SHA512Digest sha2 = new VTDev.Projects.CEX.Crypto.Digests.SHA512Digest()) hash1 = sha2.ComputeHash(buffer); using (System.Security.Cryptography.SHA512 sha = System.Security.Cryptography.SHA512Managed.Create()) hash2 = sha.ComputeHash(buffer); if (!Compare.AreEqual(hash1, hash2)) { throw new Exception("SHA256 hash is not equal!"); } } }
internal static string GetRandomNumString(int len) { char[] chars = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' }; string code = string.Empty; for (int i = 0; i < len; i++) { //这里是关键,传入一个seed参数即可保证生成的随机数不同 //Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); byte[] bytes = new byte[4]; RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); Random rnd = new Random(BitConverter.ToInt32(bytes, 0)); code += chars[rnd.Next(0, 10)].ToString(); } return(code); }
/// <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); }
public static string GetRandomSeed() { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); var tempresult = BitConverter.ToInt16(bytes, 0); var result = tempresult.ToString().Replace("-", ""); if (result.Length < 4) { result = result.PadLeft(4, '0'); } else { result = result.Substring(0, 4); } return(result); }
public static BigInteger /*!*/ Rand(RubyClass /*!*/ self, [DefaultProtocol] int bits, [DefaultProtocol, Optional] int someFlag, [Optional] bool otherFlag) // TODO: figure out someFlag and otherFlag { byte[] data = new byte[bits >> 3]; var generator = new Crypto.RNGCryptoServiceProvider(); generator.GetBytes(data); uint[] transformed = new uint[data.Length >> 2]; int j = 0; for (int i = 0; i < transformed.Length; ++i) { transformed[i] = data[j] + (uint)(data[j + 1] << 8) + (uint)(data[j + 2] << 16) + (uint)(data[j + 3] << 24); j += 4; } return(new BigInteger(transformed.SelectMany(BitConverter.GetBytes).ToArray())); }
// Return a random integer between a min and max value. private int RandomInteger(int min, int max) { uint scale = uint.MaxValue; while (scale == uint.MaxValue) { // Get four random bytes. byte[] four_bytes = new byte[4]; Rand.GetBytes(four_bytes); // Convert that into an uint. scale = BitConverter.ToUInt32(four_bytes, 0); } // Add min to the scaled difference between max and min. return((int)(min + (max - min) * (scale / (double)uint.MaxValue))); }
public IHttpActionResult GetUser() { if (players < 4 && !Gameplay.Game_Started) { //Secure hash byte[] randBytes; randBytes = new byte[100]; // Create a new RNGCryptoServiceProvider. System.Security.Cryptography.RNGCryptoServiceProvider rand = new System.Security.Cryptography.RNGCryptoServiceProvider(); // Fill the buffer with random bytes. rand.GetBytes(randBytes); MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] hash = md5.ComputeHash(randBytes); string stringhash = Convert.ToBase64String(hash); int newid = ++players; Player newplayer = new Player { ID = newid, Hash = stringhash }; try { List <Player> tempList = new List <Player>(); if (Players != null) { tempList = Players; } tempList.Add(newplayer); Players = tempList; } catch { } return(Ok(newplayer)); } else { return(NotFound()); } }
public static MutableString /*!*/ RandomBytes(RubyModule /*!*/ self, [DefaultProtocol] int length) { if (length < 0) { throw RubyExceptions.CreateArgumentError("negative string size"); } if (length == 0) { return(MutableString.CreateEmpty()); } byte[] data = new byte[length]; var generator = new Crypto.RNGCryptoServiceProvider(); generator.GetBytes(data); return(MutableString.CreateBinary(data)); }