/// <summary> /// Rearranges all the elements in the list into a highly-random order. /// </summary> /// <typeparam name="TSource">The generic type of the list.</typeparam> /// <param name="source">The input list of generic types to scramble.</param> /// <remarks>This function uses a cryptographically strong random number generator to perform the scramble.</remarks> public static void Scramble <TSource>(this IList <TSource> source) { if (source.IsReadOnly) { throw new ArgumentException("Cannot modify items in a read only list"); } int x, y; TSource currentItem; // Mixes up the data in random order. for (x = 0; x < source.Count; x++) { // Calls random function from GSF namespace. y = Random.Int32Between(0, source.Count - 1); if (x != y) { // Swaps items currentItem = source[x]; source[x] = source[y]; source[y] = currentItem; } } }
private ActionResult HandleVerifyResendCode(VerifyCodeModel formData, ConfirmableUserAccount user) { string url = m_dataContext.Connection.ExecuteScalar <string>("SELECT Value FROM DashSettings WHERE Name = 'System.URL'"); // if email changed force reconfirmation if (formData.type == "email") { // generate code for email confirmation string code = Random.Int32Between(0, 999999).ToString("D6"); s_memoryCache.Set("email" + user.ID.ToString(), code, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromDays(1) }); string emailServiceName = GetEmailServiceName(); string subject = $"{emailServiceName} requires you to confirm your email."; string body = $"From your workstation, input {code} at {url}/email/verify/email"; SendEmail(user.Email, subject, body); } // if phone changed force reconfirmation if (formData.type == "sms") { string code = Random.Int32Between(0, 999999).ToString("D6"); s_memoryCache.Set("sms" + user.ID.ToString(), code, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromDays(1) }); string emailServiceName = GetEmailServiceName(); string subject = $"{emailServiceName} requires you to confirm your SMS number."; string body = $"From your workstation, input {code} at {url}/email/verify/sms"; SendEmail(user.Phone, subject, body); } return(RedirectToAction("Verify", new { id = formData.type })); }
static void ProcessMeasurements(object state) { while (true) { List <Measurement> measurements = new List <Measurement>(); Measurement measurement; for (int i = 1; i <= MeasurementCount; i++) { measurement = new Measurement { Key = MeasurementKey.LookUpOrCreate("DEVARCHIVE", (uint)i), Value = Random.Between(-65535.0D, 65536.0D), Timestamp = DateTime.UtcNow.Ticks }; measurements.Add(measurement); } publisher.QueueMeasurementsForProcessing(measurements); Thread.Sleep(33); } }
// Static Methods /// <summary> /// Generates an "Authenticator" value used in a RADIUS request packet sent by the client to server. /// </summary> /// <param name="sharedSecret">The shared secret to be used in generating the output.</param> /// <returns>A byte array.</returns> public static byte[] CreateRequestAuthenticator(string sharedSecret) { // We create a input buffer that'll be used to create a 16-byte value using the RSA MD5 algorithm. // Since the output value (The Authenticator) has to be unique over the life of the shared secret, // we prepend a randomly generated "salt" text to ensure the uniqueness of the output value. byte[] randomBuffer = new byte[16]; byte[] secretBuffer = Encoding.GetBytes(sharedSecret); Random.GetBytes(randomBuffer); return(new MD5CryptoServiceProvider().ComputeHash(randomBuffer.Combine(secretBuffer))); }
private string IssueAuthenticationToken(string username, string password) { byte[] buffer = new byte[9]; // Generate the selector for the token Random.GetBytes(buffer); string selector = Convert.ToBase64String(buffer); // Generate the validator for the token Random.GetBytes(buffer); string validator = Convert.ToBase64String(buffer); // Determine where the credential cache is located ConfigurationFile configFile = ConfigurationFile.Current; CategorizedSettingsElementCollection systemSettings = configFile.Settings["systemSettings"]; string configurationCachePath = systemSettings["ConfigurationCachePath"].Value; string credentialCachePath = Path.Combine(configurationCachePath, "CredentialCache.bin"); // Open the credential cache lock (s_credentialCacheLock) { using (FileBackedDictionary <string, Credential> credentialCache = new FileBackedDictionary <string, Credential>(credentialCachePath)) { // Clean out expired credentials before issuing a new one DateTime now = DateTime.UtcNow; List <string> expiredSelectors = credentialCache .Where(kvp => now >= kvp.Value.Expiration) .Select(kvp => kvp.Key) .ToList(); foreach (string expiredSelector in expiredSelectors) { credentialCache.Remove(expiredSelector); } credentialCache.Compact(); // Enter the new token into the credential cache credentialCache[selector] = new Credential { Validator = validator, Username = username, Password = password, Expiration = DateTime.UtcNow.AddDays(30.0D) }; } } return($"{selector}:{validator}"); }
public void Test4() { MemoryStream ms = new MemoryStream(); BlockAllocatedMemoryStream ms2 = new BlockAllocatedMemoryStream(); for (int x = 0; x < 10000; x++) { int value = Random.Int32; ms.Write(value); ms.Write((byte)value); ms2.Write(value); ms2.Write((byte)value); } for (int x = 0; x < 10000; x++) { long position = Random.Int64Between(0, ms.Length - 5); ms.Position = position; ms2.Position = position; if (ms.ReadInt32() != ms2.ReadInt32()) { throw new Exception(); } if (ms.ReadNextByte() != ms2.ReadNextByte()) { throw new Exception(); } } for (int x = 0; x < 10000; x++) { byte[] buffer1 = new byte[100]; byte[] buffer2 = new byte[100]; long position = Random.Int64Between(0, (long)(ms.Length * 1.1)); int readLength = Random.Int32Between(0, 100); ms.Position = position; ms2.Position = position; if (ms.Read(buffer1, 99 - readLength, readLength) != ms2.Read(buffer2, 99 - readLength, readLength)) { CompareBytes(buffer1, buffer2); } } Compare(ms, ms2); }
private void HandleUpdate(UpdateSettingModel formData) { using (DataContext dataContext = new DataContext("dbOpenXDA")) using (AdoDataConnection connection = new AdoDataConnection("systemSettings")) { TableOperations <ConfirmableUserAccount> userAccountTable = dataContext.Table <ConfirmableUserAccount>(); ConfirmableUserAccount userAccount = userAccountTable.QueryRecordWhere("Name = {0}", formData.sid); string url = connection.ExecuteScalar <string>("SELECT AltText1 FROM ValueList WHERE Text = 'URL' AND GroupID = (SELECT ID FROM ValueListGroup WHERE Name = 'System')"); string emailServiceName = GetEmailServiceName(); string recipient, subject, body; // if phone changed force reconfirmation if (userAccount.Phone != formData.phone + "@" + formData.carrier) { userAccount.Phone = formData.phone; userAccount.PhoneConfirmed = false; if (!string.IsNullOrEmpty(formData.phone)) { userAccount.Phone += $"@{formData.carrier}"; // generate code for sms confirmation string code = Random.Int32Between(0, 999999).ToString("D6"); s_memoryCache.Set("sms" + userAccount.ID.ToString(), code, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromDays(1) }); recipient = userAccount.Phone; subject = $"{emailServiceName} requires you to confirm your SMS number."; body = $"From your workstation, input {code} at {url}/email/verify/sms"; SendEmail(recipient, subject, body); } } userAccountTable.UpdateRecord(userAccount); UpdateUserAccountAssetGroup(userAccount, formData); UpdateUserAccountEmailType(userAccount, formData.job, false); UpdateUserAccountEmailType(userAccount, formData.sms, true); recipient = userAccount.Email; subject = $"{emailServiceName} subscriptions updated"; body = $"Your {emailServiceName} subscriptions have been updated. Visit {url}/email/UpdateSettings to review your subscriptions."; SendEmail(recipient, subject, body); } }
/// <summary> /// Get an unused port number. /// </summary> /// <returns>An <see cref="Int32"/> value.</returns> protected virtual int GetUnusedPort() { int randomPort = Random.Int32Between(1024, 65535); IPEndPoint[] tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(); while (true) { if ((object)tcpListeners.FirstOrDefault(ep => ep.Port == randomPort) != null) { randomPort++; // Port in use - pick another one. } else { return(randomPort); // Port is not in use - use this. } } }
private void HandleUpdate(UpdateSettingModel formData) { TableOperations <ConfirmableUserAccount> userAccountTable = m_dataContext.Table <ConfirmableUserAccount>(); ConfirmableUserAccount userAccount = userAccountTable.QueryRecordWhere("Name = {0}", formData.sid); string url = m_dataContext.Connection.ExecuteScalar <string>("SELECT Value FROM DashSettings WHERE Name = 'System.URL'"); string emailServiceName = GetEmailServiceName(); string recipient, subject, body; string phone = formData.phone; string carrier = formData.carrier; if (!string.IsNullOrEmpty(phone) && !string.IsNullOrEmpty(carrier) && carrier != "0") { phone = new string(formData.phone.Where(char.IsDigit)); userAccount.Phone = $"{phone}@{carrier}"; userAccount.PhoneConfirmed = false; // generate code for sms confirmation string code = Random.Int32Between(0, 999999).ToString("D6"); s_memoryCache.Set("sms" + userAccount.ID.ToString(), code, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromDays(1) }); recipient = userAccount.Phone; subject = $"{emailServiceName} requires you to confirm your SMS number."; body = $"From your workstation, input {code} at {url}/email/verify/sms"; SendEmail(recipient, subject, body); } userAccountTable.UpdateRecord(userAccount); UpdateUserAccountAssetGroup(userAccount, formData); UpdateUserAccountEmailType(userAccount, formData.job, false); UpdateUserAccountEmailType(userAccount, formData.sms, true); recipient = userAccount.Email; subject = $"{emailServiceName} subscriptions updated"; body = $"Your {emailServiceName} subscriptions have been updated. Visit {url}/email/UpdateSettings to review your subscriptions."; SendEmail(recipient, subject, body); }
public void Test3() { MemoryStream ms = new MemoryStream(); BlockAllocatedMemoryStream ms2 = new BlockAllocatedMemoryStream(); for (int x = 0; x < 10000; x++) { long position = Random.Int64Between(0, 100000); ms.Position = position; ms2.Position = position; int value = Random.Int32; ms.Write(value); ms2.Write(value); long length = Random.Int64Between(100000 >> 1, 100000); ms.SetLength(length); ms2.SetLength(length); } Compare(ms, ms2); }
public void Test2() { MemoryStream ms = new MemoryStream(); BlockAllocatedMemoryStream ms2 = new BlockAllocatedMemoryStream(); for (int x = 0; x < 10000; x++) { int value = Random.Int32; ms.Write(value); ms2.Write(value); int seek = Random.Int16Between(-10, 20); if (ms.Position + seek < 0) { seek = -seek; } ms.Position += seek; ms2.Position += seek; } Compare(ms, ms2); }
/// <summary> /// Initializes a new instance of the <see cref="RadiusPacket"/> class. /// </summary> public RadiusPacket() { m_identifier = (byte)(Random.Between(0, 255)); m_authenticator = new byte[16]; m_attributes = new List <RadiusPacketAttribute>(); }
private static byte[] GenerateNewToken(int bitLength) { byte[] data = new byte[bitLength / 8]; Random.GetBytes(data); return(data); }
public void DataSetSerialization_ValidCase() { const int RowCount = ushort.MaxValue; // * 10;// * 20; //Act StringBuilder results = new StringBuilder(); Ticks stopTime, startTime; DataSet sourceDataSet = new DataSet("source"); DataTable table = sourceDataSet.Tables.Add("table1"); table.Columns.Add("col0", typeof(string)); table.Columns.Add("col1", typeof(int)); table.Columns.Add("col2", typeof(bool)); table.Columns.Add("col3", typeof(Guid)); table.Columns.Add("col4", typeof(DateTime)); table.Columns.Add("col5", typeof(TimeSpan)); table.Columns.Add("col6", typeof(byte[])); startTime = DateTime.UtcNow.Ticks; for (int i = 0; i < RowCount; i++) { DataRow row = table.NewRow(); if (Random.Boolean || Random.Boolean) { row[0] = new string((char)Random.Int16Between(32, 128), Random.Int16Between(5, 30)); } else { row[0] = DBNull.Value; } row[1] = Random.Int32; row[2] = Random.Boolean; if (Random.Boolean || Random.Boolean) { row[3] = Guid.NewGuid(); } else { row[3] = DBNull.Value; } row[4] = DateTime.UtcNow; row[5] = new TimeSpan(Random.Int64Between(Ticks.PerSecond, Ticks.PerHour)); byte[] bytes = null; if (Random.Boolean || Random.Boolean) { bytes = new byte[Random.Int16Between(0, 1000)]; Random.GetBytes(bytes); } row[6] = bytes; table.Rows.Add(row); } table = sourceDataSet.Tables.Add("table2"); table.Columns.Add("col0", typeof(ulong)); table.Columns.Add("col1", typeof(double)); table.Columns.Add("col2", typeof(byte)); table.Columns.Add("col3", typeof(char)); table.Columns.Add("col4", typeof(object)); for (int i = 0; i < Random.Int32Between(100, 500); i++) { DataRow row = table.NewRow(); if (Random.Boolean || Random.Boolean) { row[0] = Random.UInt64; } else { row[0] = DBNull.Value; } row[1] = Random.Number; row[2] = Random.Byte; if (Random.Boolean || Random.Boolean) { row[3] = (char)Random.Int16Between(32, 1024); } else { row[3] = DBNull.Value; } row[4] = Guid.NewGuid().ToString(); table.Rows.Add(row); } stopTime = DateTime.UtcNow.Ticks; results.AppendFormat("Initial random sample dataset created with {0} rows. ({1})\r\n", RowCount, (stopTime - startTime).ToElapsedTimeString(4)); results.AppendLine(); FileStream stream; string path = FilePath.GetApplicationDataFolder(); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string fileName = Path.Combine(path, "DataSet.bin"); startTime = DateTime.UtcNow.Ticks; stream = new FileStream(fileName, FileMode.Create); sourceDataSet.SerializeToStream(stream); stream.Flush(); stream.Close(); stream.Dispose(); stopTime = DateTime.UtcNow.Ticks; results.AppendFormat("Dataset binary serialization time: {0}\r\n", (stopTime - startTime).ToElapsedTimeString(4)); string xmlFileName = Path.Combine(path, "DataSet.xml"); startTime = DateTime.UtcNow.Ticks; sourceDataSet.WriteXml(xmlFileName, XmlWriteMode.WriteSchema); stopTime = DateTime.UtcNow.Ticks; results.AppendFormat("Dataset XML serialization time: {0}\r\n", (stopTime - startTime).ToElapsedTimeString(4)); results.AppendLine(); DataSet destinationDataSet; startTime = DateTime.UtcNow.Ticks; stream = new FileStream(fileName, FileMode.Open); destinationDataSet = stream.DeserializeToDataSet(); stream.Close(); stream.Dispose(); stopTime = DateTime.UtcNow.Ticks; results.AppendFormat("Dataset binary deserialization time: {0}\r\n", (stopTime - startTime).ToElapsedTimeString(4)); DataSet tempDataSet; startTime = DateTime.UtcNow.Ticks; tempDataSet = new DataSet(); tempDataSet.ReadXml(xmlFileName); stopTime = DateTime.UtcNow.Ticks; results.AppendFormat("Dataset XML deserialization time: {0}\r\n", (stopTime - startTime).ToElapsedTimeString(4)); results.AppendLine(); startTime = DateTime.UtcNow.Ticks; // Validate that source and destination dataset are the same Assert.AreEqual(sourceDataSet.DataSetName, destinationDataSet.DataSetName); Assert.AreEqual(sourceDataSet.Tables.Count, destinationDataSet.Tables.Count); foreach (DataTable sourceTable in sourceDataSet.Tables) { bool tableExists = destinationDataSet.Tables.Contains(sourceTable.TableName); Assert.IsTrue(tableExists); DataTable destinationTable = destinationDataSet.Tables[sourceTable.TableName]; Assert.AreEqual(sourceTable.Columns.Count, destinationTable.Columns.Count); foreach (DataColumn sourceColumn in sourceTable.Columns) { bool columnExists = destinationTable.Columns.Contains(sourceColumn.ColumnName); Assert.IsTrue(columnExists); DataColumn destinationColumn = destinationTable.Columns[sourceColumn.ColumnName]; Assert.IsTrue(sourceColumn.DataType == destinationColumn.DataType || (sourceColumn.DataType == typeof(object) && destinationColumn.DataType == typeof(string))); } Assert.AreEqual(sourceTable.Rows.Count, destinationTable.Rows.Count); for (int i = 0; i < sourceTable.Rows.Count; i++) { DataRow sourceRow = sourceTable.Rows[i]; DataRow destinationRow = destinationTable.Rows[i]; for (int j = 0; j < sourceTable.Columns.Count; j++) { if (sourceRow[j] != DBNull.Value && destinationRow[j] != DBNull.Value) { byte[] bytes = sourceRow[j] as byte[]; if ((object)bytes != null) { Assert.IsTrue(bytes.CompareTo((byte[])destinationRow[j]) == 0); } else { Assert.AreEqual(sourceRow[j], destinationRow[j]); } } } } } stopTime = DateTime.UtcNow.Ticks; results.AppendFormat("Dataset validation time: {0}\r\n", (stopTime - startTime).ToElapsedTimeString(4)); results.AppendLine(); FileInfo xmlFile = new FileInfo(xmlFileName); FileInfo binFile = new FileInfo(fileName); results.AppendFormat("Binary serialization size = {0}\r\n", SI2.ToScaledString(binFile.Length, "B")); results.AppendFormat("XML serialization size = {0}\r\n", SI2.ToScaledString(xmlFile.Length, "B")); results.AppendFormat("Size Improvement = {0:0.00%}\r\n", (xmlFile.Length - binFile.Length) / (double)xmlFile.Length); System.Console.WriteLine(results.ToString()); }
static CryptoSystem() { // Added entropy makes tokens unique to AppDomain instance of this class Random.GetBytes(s_entropy); }
/// <summary> /// Initializes a new instance of the <see cref="RadiusPacket"/> class. /// </summary> public RadiusPacket() { Identifier = (byte)Random.Between(0, 255); m_authenticator = new byte[16]; Attributes = new(); }