Esempio n. 1
0
        public void NextBytes()
        {
            byte[] data = new byte[5];
            var    rng  = new CryptoRandom();

            // ReSharper disable ReturnValueOfPureMethodIsNotUsed
            Assert.DoesNotThrow(() => rng.NextBytes(data));
            Assert.DoesNotThrow(() => rng.NextBytes(data));
            // ReSharper restore ReturnValueOfPureMethodIsNotUsed
        }
        public void EncryptedDataWithEmbededIvValidationIsValid()
        {
            using (var cr = new CryptoRandom())
            {
                for (int i = 0; i < 5; i++)
                {
                    byte[] key       = cr.NextBytes(32);
                    byte[] plainText = cr.NextBytes((uint)cr.NextInt(14, 98));

                    byte[]           encrypted = AesEncryption.EncryptAndEmbedIv(plainText, key);
                    ValidationResult result    = AesEncryption.ValidateEncryptedDataWithEmbededIv(encrypted, key);
                    Assert.True(result.IsValid);
                }
            }
        }
        /// <summary>
        /// Encrypt string with aes-256. Retrun base 64 string with salt(chars 88).
        /// </summary>
        /// <param name="plainText">The plain text string.</param>
        /// <param name="passPhrase">The password for the encryption.</param>
        /// <returns></returns>
        public static string Encrypt(string plainText, string passPhrase)
        {
            //get nedded form of passphrase and plaintest
            byte[] key = Utils.SafeUTF8.GetBytes(passPhrase);
            ArraySegment <byte> plain = new ArraySegment <byte>(Utils.SafeUTF8.GetBytes(plainText));
            //generate random salt
            CryptoRandom rng = new CryptoRandom();

            byte[] rand = rng.NextBytes(64);
            ArraySegment <byte> salt = new ArraySegment <byte>(rand);
            string ssalt             = Convert.ToBase64String(rand);

            byte[] output = null;

            output = EtM_CTR.Encrypt(key, plain, salt, rounds);

            if (output == null)
            {
                return(null);
            }

            string sout = Convert.ToBase64String(output);

            return(sout + ssalt);
        }
Esempio n. 4
0
        public byte[] GenerateRandomBytes(int size)
        {
            var bytes = new byte[size];

            Random.NextBytes(bytes);
            return(bytes);
        }
        protected override Task Handle(RegisterRequest packet, ISession session)
        {
            if (packet.Key != "alohamora321")
            {
                return(Return(session));
            }

            var account = _accountService.GetByUsername(packet.Username);

            if (account != null)
            {
                return(Return(session));
            }

            var salt = new byte[16];

            _rng.NextBytes(salt);
            _argon2.Salt = salt;
            _argon2.Hash = _argon2.HashWithSpec(packet.PasswordHash);

            _accountService.Save(new AccountModel
            {
                Username       = packet.Username,
                EncodedHash    = _argon2.GetEncodedHash(),
                TimeOfCreation = DateTime.UtcNow
            });

            session.SendPacket(new RegisterResponse {
                RegisterResponseType = RegisterResponseType.Registered
            });

            return(Task.CompletedTask);
        }
Esempio n. 6
0
        public byte[] Get()
        {
            var bytes        = new byte[15];
            var cryptoRandom = new CryptoRandom();

            cryptoRandom.NextBytes(bytes);
            return(bytes);
        }
Esempio n. 7
0
        public void NextBytes_Throws()
        {
            var rng = new CryptoRandom();

            // ReSharper disable ReturnValueOfPureMethodIsNotUsed
            // ReSharper disable once AssignNullToNotNullAttribute
            Assert.Throws <ArgumentNullException>(() => rng.NextBytes(null));
        }
		public void CryptoRandom_NeutralParity()
		{
			byte[] random = new byte[2048];

			var rng = new CryptoRandom();
			rng.NextBytes(random);

			AssertNeutralParity(random);
		}
Esempio n. 9
0
		}//ctor

		static byte[] GenerateSalt(int saltSize)
		{
			if (saltSize < 0)
				throw new ArgumentOutOfRangeException(nameof(saltSize));

			byte[] data = new byte[saltSize];
			rng.NextBytes(data);
			return data;
		}//GenerateSalt()
        public void NextBytes_With_Null_Buffer_Generates_Exception()
        {
            var cryptoRandom = new CryptoRandom();

            // ReSharper disable once AssignNullToNotNullAttribute
            Action act = () => cryptoRandom.NextBytes(null);

            act.Should().Throw <ArgumentNullException>();
        }
Esempio n. 11
0
		public void CryptoRandom_NeutralParity()
		{
			byte[] random = new byte[2048];

			var rng = new CryptoRandom();
			rng.NextBytes(random);

			AssertNeutralParity(random);
		}
Esempio n. 12
0
		static void DifferentSequential(int arraySize)
		{
			// Ensure that the RNG doesn't produce a stable set of data.
			byte[] first = new byte[arraySize];
			byte[] second = new byte[arraySize];

			var rng = new CryptoRandom();
			rng.NextBytes(first);
			rng.NextBytes(second);

			// Random being random, there is a chance that it could produce the same sequence.
			// The smallest test case that we have is 10 bytes.
			// The probability that they are the same, given a Truly Random Number Generator is:
			// Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
			// = 1/256 * 1/256 * ... * 1/256
			// = 1/(256^10)
			// = 1/1,208,925,819,614,629,174,706,176
			Assert.AreNotEqual(first, second);
		}
Esempio n. 13
0
        public void EncryptedWithEmbeddedIvCanBeDecrypted()
        {
            using (var cr = new CryptoRandom())
            {
                for (int i = 0; i < 5; i++)
                {
                    byte[] key       = cr.NextBytes(32);
                    byte[] plainText = cr.NextBytes((uint)cr.NextInt(4 * 1025, 8 * 1025));

                    byte[] encrypted = AesEncryption.EncryptAndEmbedIv(plainText, key);
                    byte[] decrypted = AesEncryption.DecryptWithEmbeddedIv(encrypted, key);

                    string plainString     = Convert.ToBase64String(plainText);
                    string decryptedString = Convert.ToBase64String(decrypted);

                    Assert.Equal(plainString, decryptedString);
                }
            }
        }
        public void EncryptedDataWithEmbededIvFailsKcvWhenKeyIsAltered()
        {
            using (var cr = new CryptoRandom())
            {
                for (int i = 0; i < 5; i++)
                {
                    byte[] key       = cr.NextBytes(32);
                    byte[] plainText = cr.NextBytes((uint)cr.NextInt(14, 98));

                    byte[] encrypted = AesEncryption.EncryptAndEmbedIv(plainText, key);
                    AlterData(key, 0);

                    ValidationResult result = AesEncryption.ValidateEncryptedDataWithEmbededIv(encrypted, key);
                    Assert.False(result.IsValid);
                    Assert.False(result.KeyIsValid);
                    Assert.Equal(result.ErrorType.Value, DataValidationErrors.KeyCheckValueValidationError);
                }
            }
        }
        public void EncryptedDataWithAlteredMacWillFailMacValidation()
        {
            using (var cr = new CryptoRandom())
            {
                for (int i = 0; i < 5; i++)
                {
                    byte[] key       = cr.NextBytes(32);
                    byte[] iv        = cr.NextBytes(16);
                    byte[] plainText = cr.NextBytes((uint)cr.NextInt(14, 98));

                    byte[] encrypted = AesEncryption.Encrypt(plainText, key, iv);
                    AlterData(encrypted, 76); // alter MAC

                    ValidationResult result = AesEncryption.ValidateEncryptedData(encrypted, key, iv);
                    Assert.False(result.IsValid);
                    Assert.False(result.DataIntegrityIsValid);
                    Assert.Equal(result.ErrorType.Value, DataValidationErrors.DataIntegrityValidationError);
                }
            }
        }
        public void EncryptedDataValidationFailsKcvOnChangedKey()
        {
            using (var cr = new CryptoRandom())
            {
                for (int i = 0; i < 5; i++)
                {
                    byte[] key       = cr.NextBytes(32);
                    byte[] iv        = cr.NextBytes(16);
                    byte[] plainText = cr.NextBytes((uint)cr.NextInt(14, 98));

                    byte[] encrypted = AesEncryption.Encrypt(plainText, key, iv);
                    AlterData(key, 0); // change key

                    ValidationResult result = AesEncryption.ValidateEncryptedData(encrypted, key, iv);
                    Assert.False(result.IsValid);
                    Assert.False(result.KeyIsValid);
                    Assert.Equal(result.ErrorType.Value, DataValidationErrors.KeyCheckValueValidationError);
                }
            }
        }
Esempio n. 17
0
        private void TestEncryptDecrypt(uint keySize)
        {
            using (var cr = new CryptoRandom())
            {
                for (int i = 0; i < 5; i++)
                {
                    byte[] key       = cr.NextBytes(keySize);
                    byte[] iv        = cr.NextBytes(16);
                    byte[] plainText = cr.NextBytes((uint)cr.NextInt(1, 2455));

                    byte[] encrypted = AesEncryption.Encrypt(plainText, key, iv);
                    byte[] decrypted = AesEncryption.Decrypt(encrypted, key, iv);

                    string plainString     = Convert.ToBase64String(plainText);
                    string decryptedString = Convert.ToBase64String(decrypted);

                    Assert.Equal(plainString, decryptedString);
                }
            }
        }
Esempio n. 18
0
        public void ByteArray_Basic()
        {
            var     rnd        = new CryptoRandom();
            int     itemsCount = 1_000;
            BVector d          = new BVector();

            byte[] values = rnd.NextBytes(itemsCount);

            d.Add(values);
            Assert.IsTrue(BHelper.CompareByteArrays(values, d.GetByteArray()));
        }
Esempio n. 19
0
		public void CryptoRandom_NullInput1()
		{
			var rng = new CryptoRandom();
			try
			{
				rng.NextBytes(null); // should throw
			}
			catch (NullReferenceException)
			{
				Assert.IsTrue(true);
				return;
			}
			Assert.Fail("Failed to throw NullReferenceException.");
		}
Esempio n. 20
0
		public void CryptoRandom_NullInput2()
		{
			var rng = new CryptoRandom();
			try
			{
				rng.NextBytes(null, 0, 0); // should throw
			}
			catch (ArgumentNullException)
			{
				Assert.IsTrue(true);
				return;
			}
			Assert.Fail("Failed to throw ArgumentNullException.");
		}
Esempio n. 21
0
		public void CryptoRandom_ZeroLengthInput()
		{
			var rng = new CryptoRandom();

			// While this will do nothing, it's not something that throws.
			rng.NextBytes(Array.Empty<byte>());
			rng.NextBytes(Array.Empty<byte>(), 0, 0);

			bool isThrown = false;
			try
			{
				rng.NextBytes(Array.Empty<byte>(), 0, 123);
			}
			catch (ArgumentException) { isThrown = true; }
			Assert.IsTrue(isThrown);

			isThrown = false;
			try
			{
				rng.NextBytes(Array.Empty<byte>(), 123, 0);
			}
			catch (ArgumentException) { isThrown = true; }
			Assert.IsTrue(isThrown);
		}
        public void NextBytes_Generates_Random_Bytes_Within_Range()
        {
            // arrange
            var cryptoRandom = new CryptoRandom();

            var bytes = new byte[10];

            // act
            cryptoRandom.NextBytes(bytes);

            // assert
            foreach (var randomByte in bytes)
            {
                randomByte.Should().BeInRange(0, 255);
            }
        }
Esempio n. 23
0
        public void EncryptedDataWithAdditionalDataCanBeDecrypted()
        {
            for (int i = 0; i < NumberOrTestRuns; i++)
            {
                using (CryptoRandom cr = new CryptoRandom())
                {
                    string password  = Guid.NewGuid().ToString();
                    byte[] plainText = cr.NextBytes((uint)cr.NextInt(44, 444));
                    byte[] encrypted = AesEncryption.EncryptWithPassword(plainText, password);
                    byte[] encryptedWithAdditionalData = AesEncryptionAdditionalData.AddAdditionalData(encrypted, additionalData);

                    byte[] decrypted = AesEncryption.DecryptWithPassword(encrypted, password);
                    Assert.Equal(Convert.ToBase64String(plainText), Convert.ToBase64String(decrypted));
                }
            }
        }
Esempio n. 24
0
        public ActionResult changePassword(string id, changePassword pass)
        {
            try
            {
                using (Notestash_Database_Entities db = new Notestash_Database_Entities())
                {
                    if (pass.newPassword.Equals(pass.confirmNewPassword) && pass.newPassword.Length >= 6 && pass.newPassword.Length <= 15)
                    {
                        var    passwordChanged = db.tblUsers.Where(e => e.forgotPasswordCode == new Guid(id)).FirstOrDefault();
                        string newPass         = pass.newPassword;

                        var sha384Factory = HmacFactory;
                        var random        = new CryptoRandom();

                        byte[] derivedKey;
                        string hashedPassword = null;
                        string passwordText   = newPass;

                        byte[] passwordBytes = SafeUTF8.GetBytes(passwordText);
                        var    salt          = random.NextBytes(384 / 8);

                        using (var pbkdf2 = new PBKDF2(sha384Factory, passwordBytes, salt, 256 * 1000))
                            derivedKey = pbkdf2.GetBytes(384 / 8);


                        using (var hmac = sha384Factory())
                        {
                            hmac.Key       = derivedKey;
                            hashedPassword = hmac.ComputeHash(passwordBytes).ToBase16();
                        }

                        passwordChanged.Password           = hashedPassword;
                        passwordChanged.Salt               = salt;
                        passwordChanged.forgotPasswordCode = null;
                        db.SaveChanges();
                        ModelState.AddModelError("Changed", "Password changed successfully!");
                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                ModelState.AddModelError("BadRequest", "Error occurred, please try again!");
            }
            return(View());
        }
Esempio n. 25
0
        public void EncryptedWithPasswordCanBeDecrypted()
        {
            using (var cr = new CryptoRandom())
            {
                for (int i = 0; i < 5; i++)
                {
                    string password  = PasswordGenerator.GenerateStatic();
                    byte[] plainText = cr.NextBytes((uint)cr.NextInt(4 * 1025, 8 * 1025));

                    byte[] encrypted = AesEncryption.EncryptWithPassword(plainText, password);
                    byte[] decrypted = AesEncryption.DecryptWithPassword(encrypted, password);

                    string plainString     = Convert.ToBase64String(plainText);
                    string decryptedString = Convert.ToBase64String(decrypted);

                    Assert.Equal(plainString, decryptedString);
                }
            }
        }
Esempio n. 26
0
		public void CryptoRandom_ConcurrentAccess()
		{
			const int ParallelTasks = 16;
			const int PerTaskIterationCount = 20;
			const int RandomSize = 1024;

			var tasks = new System.Threading.Tasks.Task[ParallelTasks];
			byte[][] taskArrays = new byte[ParallelTasks][];

			var rng = new CryptoRandom();
			using (var sync = new System.Threading.ManualResetEvent(false))
			{
				for (int iTask = 0; iTask < ParallelTasks; iTask++)
				{
					taskArrays[iTask] = new byte[RandomSize];
					byte[] taskLocal = taskArrays[iTask];

					tasks[iTask] = Task.Factory.StartNew(
						() =>
						{
							sync.WaitOne();

							for (int i = 0; i < PerTaskIterationCount; i++)
							{
								rng.NextBytes(taskLocal);
							}
						}, TaskCreationOptions.LongRunning);
				}

				// Ready? Set() Go!
				sync.Set();
				Task.WaitAll(tasks);
			}

			for (int i = 0; i < ParallelTasks; i++)
			{
				// The Real test would be to ensure independence of data, but that's difficult.
				// The other end of the spectrum is to test that they aren't all just new byte[RandomSize].
				// Middle ground is to assert that each of the chunks has neutral(ish) bit parity.
				AssertNeutralParity(taskArrays[i]);
			}
		}
Esempio n. 27
0
        public HttpResponseMessage changePassword(string id, changePassword pass)
        {
            try
            {
                using (Notestash_DatabaseEntities db = new Notestash_DatabaseEntities())
                {
                    var    passwordChanged = db.tblUsers.Where(e => e.forgotPasswordCode == new Guid(id)).FirstOrDefault();
                    string newPass         = pass.newPassword;

                    var sha384Factory = HmacFactory;
                    var random        = new CryptoRandom();

                    byte[] derivedKey;
                    string hashedPassword = null;
                    string passwordText   = newPass;

                    byte[] passwordBytes = SafeUTF8.GetBytes(passwordText);
                    var    salt          = random.NextBytes(384 / 8);

                    using (var pbkdf2 = new PBKDF2(sha384Factory, passwordBytes, salt, 256 * 1000))
                        derivedKey = pbkdf2.GetBytes(384 / 8);


                    using (var hmac = sha384Factory())
                    {
                        hmac.Key       = derivedKey;
                        hashedPassword = hmac.ComputeHash(passwordBytes).ToBase16();
                    }

                    passwordChanged.Password           = hashedPassword;
                    passwordChanged.Salt               = salt;
                    passwordChanged.forgotPasswordCode = null;
                    db.SaveChanges();
                    return(Request.CreateResponse(HttpStatusCode.OK, "Password changed successfully!"));
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error occurred, please try again!"));
            }
        }
Esempio n. 28
0
		static void DifferentParallel(int arraySize)
		{
			// Ensure that two RNGs don't produce the same data series (such as being implemented via new Random(1)).
			byte[] first = new byte[arraySize];
			byte[] second = new byte[arraySize];

			var rng1 = new CryptoRandom();
			var rng2 = new CryptoRandom();

			rng1.NextBytes(first);
			rng2.NextBytes(second);

			// Random being random, there is a chance that it could produce the same sequence.
			// The smallest test case that we have is 10 bytes.
			// The probability that they are the same, given a Truly Random Number Generator is:
			// Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
			// = 1/256 * 1/256 * ... * 1/256
			// = 1/(256^10)
			// = 1/1,208,925,819,614,629,174,706,176
			Assert.AreNotEqual(first, second);
		}
        private string WriteToTempFile(int length)
        {
            var filePath = Path.GetTempFileName();

            byte[] buffer;
            int    written    = 0;
            int    bufferSize = 4 * 1024;
            int    toWrite;

            using (Stream fileStream = new FileStream(filePath, FileMode.Create))
                using (CryptoRandom rand = new CryptoRandom())
                {
                    buffer = rand.NextBytes(4 * 1024);
                    while (written < length)
                    {
                        toWrite = (written + bufferSize < length) ? bufferSize : length - written;
                        fileStream.Write(buffer, 0, toWrite);
                        written += toWrite;
                    }
                }
            return(filePath);
        }
Esempio n. 30
0
		static void Main(string[] args)
		{
			const bool SEEDED_TEST = false;
			const long ITER = 10_000_000L * 2L;
			const bool IS_SEQUENTIAL = false;
			const bool IS_PARALLEL = true;

			if (SEEDED_TEST)
			{
				var seedkey = new byte[CryptoRandom.Params.Seeded.SEEDKEY_SIZE];
				var seeded = new CryptoRandom(seedkey);

				Span<byte> data = new byte[256];

				seeded.Reseed(seedkey);
				seeded.NextBytes(data);
				Convert.ToHexString(data).Dump();

				data.Clear();
				//seeded = new SeededCryptoRandomImpl(seedkey); 
				seeded.Reseed(seedkey);
				for (int i = 0; i < data.Length; ++i)
				{
					seeded.NextBytes(data.Slice(i, 1));
					Convert.ToHexString(data.Slice(0, i + 1)).Dump(); Console.WriteLine("====================");
				}

				return;
			}
			var sw = new Stopwatch();

            $".NET: [{Environment.Version}]".Dump();
			$"{nameof(Environment.ProcessorCount)}: {Environment.ProcessorCount}".Dump();
			$"{nameof(CryptoRandom.Params.RNG.BYTE_CACHE_SIZE)}: {CryptoRandom.Params.RNG.BYTE_CACHE_SIZE}".Dump();
			$"{nameof(CryptoRandom.Params.RNG.REQUEST_CACHE_LIMIT)}: {CryptoRandom.Params.RNG.REQUEST_CACHE_LIMIT}".Dump();
			$"{nameof(TestStruct)} Size: {Utils.StructSizer<TestStruct>.Size}\n".Dump();


			for (int _ = 0; _ < 4; ++_)
			{
				Guid g = default;
				cr.Next(ref g);
				g.Dump();
			}
			"".Dump();
			//return;
			const int REPS = 5;


			IS_SEQUENTIAL.Dump(nameof(IS_SEQUENTIAL));
			IS_PARALLEL.Dump(nameof(IS_PARALLEL));

			for (int j = 0; j < REPS; ++j)
			{
				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						var data = default(TestStruct);
						var span = Utils.AsSpan(ref data);
						cr.NextBytes(span);
					});
					sw.Stop();
					$"{sw.Elapsed} Utils.AsSpan(ref data); cr.NextBytes(span);".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						var data = default(TestStruct);
						cr.Next(ref data);
					});
					sw.Stop();
					$"{sw.Elapsed} cr.Next(ref data);".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						var data = default(TestStruct);
						CryptoRandom.Shared.Next(ref data);
					});
					sw.Stop();
					$"{sw.Elapsed} CryptoRandom.Shared.Next(ref data);".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.NextGuid();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.NextGuid();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.Next<Guid>();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.Next<Guid>();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						Guid.NewGuid();
					});
					sw.Stop();
					$"{sw.Elapsed} Guid.NewGuid();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.SqlServerGuid();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.SqlServerGuid();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.Next();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.Next();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.NextDouble();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.NextDouble();".Dump();
				}

				{
					sw.Restart();
					Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i =>
					{
						cr.NextSingle();
					});
					sw.Stop();
					$"{sw.Elapsed} cr.NextSingle();".Dump();
				}
				"".Dump();
			}// REPS
		}//Main()
		public void EtM_CTR_Sanity()
		{
			var rnd = new CryptoRandom();
			const int plaintextOffset = 16;

			for (int i = 0; i < 2000; ++i)
			{
				var plaintext = new byte[rnd.Next(plaintextOffset + plaintextOffset, 50 * 1024)];
				var plaintextSegment = new ArraySegment<byte>(array: plaintext, offset: plaintextOffset /* some non-zero offset */, count: plaintext.Length - plaintextOffset - plaintextOffset);
				rnd.NextBytes(plaintext);
				var masterkey = new byte[rnd.Next(0, 64)];
				rnd.NextBytes(masterkey);

				var salt = new byte[rnd.Next(0, 64)];
				rnd.NextBytes(salt);
				var saltSegment = new ArraySegment<byte>(salt);

				var ciphertext = EtM_CTR.Encrypt(masterkey, plaintextSegment, saltSegment);
				var ciphertext_with_padding = new byte[ciphertext.Length + plaintextOffset + plaintextOffset];
				Utils.BlockCopy(ciphertext, 0, ciphertext_with_padding, plaintextOffset, ciphertext.Length);

				var ciphertextSegment = new ArraySegment<byte>(array: ciphertext_with_padding, offset: plaintextOffset, count: ciphertext.Length);

				var decryptedtext = EtM_CTR.Decrypt(masterkey, ciphertextSegment, saltSegment);
				Assert.IsTrue(Utils.ConstantTimeEqual(new ArraySegment<byte>(decryptedtext), plaintextSegment));

				Assert.IsTrue(EtM_CTR.Authenticate(masterkey, ciphertextSegment, saltSegment));
			}//for
		}//EtM_CTR_Sanity()
Esempio n. 32
0
 public void NextBytes()
 {
     var random = new CryptoRandom();
     var buffer = new byte[10];
     Assert.DoesNotThrow(() => random.NextBytes(buffer));
 }
		static void DifferentParallel(int arraySize)
		{
			// Ensure that two RNGs don't produce the same data series (such as being implemented via new Random(1)).
			byte[] first = new byte[arraySize];
			byte[] second = new byte[arraySize];

			var rng1 = new CryptoRandom();
			var rng2 = new CryptoRandom();

			rng1.NextBytes(first);
			rng2.NextBytes(second);

			// Random being random, there is a chance that it could produce the same sequence.
			// The smallest test case that we have is 10 bytes.
			// The probability that they are the same, given a Truly Random Number Generator is:
			// Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
			// = 1/256 * 1/256 * ... * 1/256
			// = 1/(256^10)
			// = 1/1,208,925,819,614,629,174,706,176
			Assert.AreNotEqual(first, second);
		}
		public void Base64_ToB64Url_Test()
		{
			var rnd = new CryptoRandom();
			Parallel.For(1, 5000, i =>
			{
				var byteArray = rnd.NextBytes(i);
				var offset = 0;
				var count = Math.Max(i, i - rnd.Next(10));
				var byteSegment = new ArraySegment<byte>(byteArray, offset, count);

				var b64url = byteSegment.ToB64Url();
				var b64 = byteSegment.ToB64();

				Assert.IsTrue(b64url + b64[b64.Length - 1] == b64);
				Assert.IsTrue(Enumerable.SequenceEqual(byteSegment, b64url.FromB64Url()));
			});
		}// Base64_ToB64Url_Test()
		public void CryptoRandom_ZeroLengthInput()
		{
			var rng = new CryptoRandom();
			// While this will do nothing, it's not something that throws.
			rng.NextBytes(Utils.ZeroLengthArray<byte>.Value);
		}
Esempio n. 36
0
        static void Main(string[] args)
        {
            // Set colors to green on black, because everyone knows that's what hackers use
            Console.ForegroundColor = ConsoleColor.Green;
            Console.BackgroundColor = ConsoleColor.Black;
            Console.Clear();

            // Show banner
            Console.WriteLine("Developer Secrets Receiver - Generation 3 (symmetric encryption with key derivation)");
            Console.WriteLine("Copyright (c) Michal A. Valasek - Altairis, 2016");
            Console.WriteLine(new string('-', Console.WindowWidth - 1));
            Console.WriteLine();

            // Create master symmetric key
            var rnd             = new CryptoRandom();
            var masterKey       = rnd.NextBytes(32);
            var masterKeyString = masterKey.ToBase16();

            Console.WriteLine("This is your master symmetric key: " + masterKeyString);
            Console.WriteLine("Send it to your chat partner safely!");
            Console.WriteLine();

            // Get queue
            var q = GetQueue(CONNECTION_STRING, QUEUE_NAME);

            // Main loop
            Console.WriteLine("Waiting for messages. Press SPACEBAR for pause, ESC for exit.");
            Console.WriteLine();

            uint expectedMessageNumber = 1;

            while (true)
            {
                // Wait to receive message
                var msg = q.GetMessage();
                if (msg == null)
                {
                    // No more messages
                    if (Console.KeyAvailable)
                    {
                        var keyCode = Console.ReadKey(intercept: true);
                        if (keyCode.Key == ConsoleKey.Escape)
                        {
                            break;
                        }
                        if (keyCode.Key == ConsoleKey.Spacebar)
                        {
                            Console.WriteLine();
                            Console.WriteLine("Paused, press any key to continue...");
                            Console.ReadKey(intercept: true);
                            Console.WriteLine("Waiting for messages. Press SPACEBAR for pause, ESC for exit.");
                            Console.WriteLine();
                        }
                    }
                    Thread.Sleep(250);
                    continue;
                }

                // Delete message from queue
                q.DeleteMessage(msg);

                // Parse message
                var  messageParts  = msg.AsString.Split('|');
                uint messageNumber = uint.Parse(messageParts[0]);
                var  cipherData    = messageParts[1].FromBase16();

                // Validate message number
                if (messageNumber < expectedMessageNumber)
                {
                    // Received number is too low - message is repeated or out of order
                    Console.WriteLine($"WARNING! The following message has too low serial number (expected {expectedMessageNumber}, got {messageNumber}.");
                    Console.WriteLine($"         Message is repeated or was delivered out of order.");
                }
                else if (messageNumber > expectedMessageNumber)
                {
                    // Received number is too high - some messages are missing or out of order
                    Console.WriteLine($"WARNING! The following message has too high serial number (expected {expectedMessageNumber}, got {messageNumber}.");
                    Console.WriteLine($"         Message was delivered out of order or some messages are missing.");
                    expectedMessageNumber = messageNumber + 1;
                }
                else
                {
                    // Received number is correct
                    expectedMessageNumber++;
                }

                // Derive key using HKDF algorithm
                var context    = BitConverter.GetBytes(messageNumber);
                var derivedKey = new byte[32].AsArraySegment();
                SP800_108_Ctr.DeriveKey(HMACFactories.HMACSHA256, masterKey, null, context.AsArraySegment(), derivedKey, messageNumber);

                // Authenticate message
                var authenticated = SuiteB.Authenticate(derivedKey.Array, cipherData.AsArraySegment());
                if (!authenticated)
                {
                    Console.WriteLine($"< Message #{messageNumber} ({msg.Id}) from {msg.InsertionTime:yyyy-MM-dd HH:mm:ss} was tampered with!");
                    continue;
                }

                // Decrypt message
                var plainData   = SuiteB.Decrypt(derivedKey.Array, cipherData.AsArraySegment());
                var plainString = plainData.FromBytes();

                // Display message
                Console.WriteLine($"< Message #{messageNumber} ({msg.Id}) from {msg.InsertionTime:yyyy-MM-dd HH:mm:ss}:");
                Console.WriteLine(plainString);
            }

            Console.WriteLine("Program terminated successfully.");
        }
		public void CryptoRandom_NullInput()
		{
			var rng = new CryptoRandom();
			try
			{
				rng.NextBytes(null); // should throw
			}
			catch (NullReferenceException)
			{
				Assert.IsTrue(true);
				return;
			}
			Assert.Fail("Failed to throw NullReferenceException.");
		}
		public void CryptoRandom_ConcurrentAccess()
		{
			const int ParallelTasks = 16;
			const int PerTaskIterationCount = 20;
			const int RandomSize = 1024;

			var tasks = new System.Threading.Tasks.Task[ParallelTasks];
			byte[][] taskArrays = new byte[ParallelTasks][];

			var rng = new CryptoRandom();
			using (var sync = new System.Threading.ManualResetEvent(false))
			{
				for (int iTask = 0; iTask < ParallelTasks; iTask++)
				{
					taskArrays[iTask] = new byte[RandomSize];
					byte[] taskLocal = taskArrays[iTask];

					tasks[iTask] = System.Threading.Tasks.Task.Run(
						() =>
						{
							sync.WaitOne();

							for (int i = 0; i < PerTaskIterationCount; i++)
							{
								rng.NextBytes(taskLocal);
							}
						});
				}

				// Ready? Set() Go!
				sync.Set();
				System.Threading.Tasks.Task.WaitAll(tasks);
			}

			for (int i = 0; i < ParallelTasks; i++)
			{
				// The Real test would be to ensure independence of data, but that's difficult.
				// The other end of the spectrum is to test that they aren't all just new byte[RandomSize].
				// Middle ground is to assert that each of the chunks has neutral(ish) bit parity.
				AssertNeutralParity(taskArrays[i]);
			}
		}
		public void CryptoRandom_ZeroLengthInput()
		{
			var rng = new CryptoRandom();

			// While this will do nothing, it's not something that throws.
			rng.NextBytes(Utils.ZeroLengthArray<byte>.Value);
			rng.NextBytes(Utils.ZeroLengthArray<byte>.Value, 0, 0);

			bool isThrown = false;
			try
			{
				rng.NextBytes(Utils.ZeroLengthArray<byte>.Value, 0, 123);
			}
			catch (ArgumentException) { isThrown = true; }
			Assert.IsTrue(isThrown);

			isThrown = false;
			try
			{
				rng.NextBytes(Utils.ZeroLengthArray<byte>.Value, 123, 0);
			}
			catch (ArgumentException) { isThrown = true; }
			Assert.IsTrue(isThrown);
		}
		static void DifferentSequential(int arraySize)
		{
			// Ensure that the RNG doesn't produce a stable set of data.
			byte[] first = new byte[arraySize];
			byte[] second = new byte[arraySize];

			var rng = new CryptoRandom();
			rng.NextBytes(first);
			rng.NextBytes(second);

			// Random being random, there is a chance that it could produce the same sequence.
			// The smallest test case that we have is 10 bytes.
			// The probability that they are the same, given a Truly Random Number Generator is:
			// Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
			// = 1/256 * 1/256 * ... * 1/256
			// = 1/(256^10)
			// = 1/1,208,925,819,614,629,174,706,176
			Assert.AreNotEqual(first, second);
		}
		public void CryptoRandom_NullInput2()
		{
			var rng = new CryptoRandom();
			try
			{
				rng.NextBytes(null, 0, 0); // should throw
			}
			catch (ArgumentNullException)
			{
				Assert.IsTrue(true);
				return;
			}
			Assert.Fail("Failed to throw ArgumentNullException.");
		}