Пример #1
1
        public String GeneratePassword(int length, bool upperCase, bool lowerCase, bool digits, bool minus, bool underline, bool space, bool specials, bool brackets)
        {
            if (length <= 0)
                throw new ArgumentException(_cxt.GetString(Resource.String.error_wrong_length));

            if (!upperCase && !lowerCase && !digits && !minus && !underline && !space && !specials && !brackets)
                throw new ArgumentException(_cxt.GetString(Resource.String.error_pass_gen_type));

            String characterSet = GetCharacterSet(upperCase, lowerCase, digits, minus, underline, space, specials, brackets);

            int size = characterSet.Length;

            StringBuilder buffer = new StringBuilder();

            Random random = new SecureRandom();
            if (size > 0)
            {
                for (int i = 0; i < length; i++)
                {
                    char c = characterSet[random.Next(size)];

                    buffer.Append(c);
                }
            }

            return buffer.ToString();
        }
Пример #2
0
		private void doTestCreateKeyParameter(
			string				algorithm,
			DerObjectIdentifier	oid,
			int					keyBits,
			Type				expectedType,
			SecureRandom		random)
		{
			int keyLength = keyBits / 8;
			byte[] bytes = new byte[keyLength];
			random.NextBytes(bytes);

			KeyParameter key;

			key = ParameterUtilities.CreateKeyParameter(algorithm, bytes);
			checkKeyParameter(key, expectedType, bytes);

			key = ParameterUtilities.CreateKeyParameter(oid, bytes);
			checkKeyParameter(key, expectedType, bytes);

			bytes = new byte[keyLength * 2];
			random.NextBytes(bytes);

			int offset = random.Next(1, keyLength);
			byte[] expected = new byte[keyLength];
			Array.Copy(bytes, offset, expected, 0, keyLength);

			key = ParameterUtilities.CreateKeyParameter(algorithm, bytes, offset, keyLength);
			checkKeyParameter(key, expectedType, expected);

			key = ParameterUtilities.CreateKeyParameter(oid, bytes, offset, keyLength);
			checkKeyParameter(key, expectedType, expected);
		}
Пример #3
0
 private byte[] randomBlocks(int upper)
 {
     byte[] bs = new byte[16 * random.Next(upper)];
     random.NextBytes(bs);
     return(bs);
 }
        /// <summary>
        /// Safely get Crypto Random byte array at the size you desire.
        /// </summary>
        /// <param name="size">Size of the crypto random byte array to build</param>
        /// <param name="seedStretchingIterations">Optional parameter to specify how many SHA512 passes occur over our seed before we use it. Higher value is greater security but uses more computational power. If random byte generation is taking too long try specifying values lower than the default of 5000. You can set 0 to turn off stretching</param>
        /// <returns>A byte array of completely random bytes</returns>
        public static byte[] GetRandomBytes(int size, int seedStretchingIterations = 5000)
        {
            //varies from system to system, a tiny amount of entropy, tiny
            int processorCount = System.Environment.ProcessorCount;

            //another tiny amount of entropy due to the varying nature of thread id
            int currentThreadId = System.Environment.CurrentManagedThreadId;

            //a GUID is considered unique so also provides some entropy
            byte[] guidBytes = Guid.NewGuid().ToByteArray();

            //this combined with DateTime.Now is the default seed in BouncyCastles SecureRandom
            byte[] threadedSeedBytes = new ThreadedSeedGenerator().GenerateSeed(24, true);

            byte[] output = new byte[size];

            //if for whatever reason it says 0 or less processors just make it 16
            if (processorCount <= 0)
            {
                processorCount = 16;
            }

            //if some fool trys to set stretching to < 0 we protect them from themselves
            if (seedStretchingIterations < 0)
            {
                seedStretchingIterations = 0;
            }

            //we create a SecureRandom based off SHA256 just to get a random int which will be used to determine what bytes to "take" from our built seed hash and then rehash those taken seed bytes using a KDF (key stretching) such that it would slow down anyone trying to rebuild private keys from common seeds.
            SecureRandom seedByteTakeDetermine = SecureRandom.GetInstance("SHA256PRNG");

            guidBytes = HmacSha512Digest(guidBytes, 0, guidBytes.Length, MergeByteArrays(threadedSeedBytes, UTF8Encoding.UTF8.GetBytes(Convert.ToString(System.Environment.TickCount))));

            try
            {
                seedByteTakeDetermine.SetSeed(((DateTime.Now.Ticks - System.Environment.TickCount) * processorCount) + currentThreadId);
                seedByteTakeDetermine.SetSeed(guidBytes);
                seedByteTakeDetermine.SetSeed(seedByteTakeDetermine.GenerateSeed(1 + currentThreadId));
                seedByteTakeDetermine.SetSeed(threadedSeedBytes);
            }
            catch
            {
                try
                {
                    //if the number is too big or causes an error or whatever we will failover to this, as it's not our main source of random bytes and not used in the KDF stretching it's ok.
                    seedByteTakeDetermine.SetSeed((DateTime.Now.Ticks - System.Environment.TickCount) + currentThreadId);
                    seedByteTakeDetermine.SetSeed(guidBytes);
                    seedByteTakeDetermine.SetSeed(seedByteTakeDetermine.GenerateSeed(1 + currentThreadId));
                    seedByteTakeDetermine.SetSeed(threadedSeedBytes);
                }
                catch
                {
                    //if again the number is too big or causes an error or whatever we will failover to this, as it's not our main source of random bytes and not used in the KDF stretching it's ok.
                    seedByteTakeDetermine.SetSeed(DateTime.Now.Ticks - System.Environment.TickCount);
                    seedByteTakeDetermine.SetSeed(guidBytes);
                    seedByteTakeDetermine.SetSeed(seedByteTakeDetermine.GenerateSeed(1 + currentThreadId));
                    seedByteTakeDetermine.SetSeed(threadedSeedBytes);
                }
            }

            //hardened seed
            byte[] toHashForSeed;

            try
            {
                toHashForSeed = BitConverter.GetBytes(((processorCount - seedByteTakeDetermine.Next(0, processorCount)) * System.Environment.TickCount) * currentThreadId);
            }
            catch
            {
                try
                {
                    //if the number was too large or something we failover to this
                    toHashForSeed = BitConverter.GetBytes(((processorCount - seedByteTakeDetermine.Next(0, processorCount)) + System.Environment.TickCount) * currentThreadId);
                }
                catch
                {
                    //if the number was again too large or something we failover to this
                    toHashForSeed = BitConverter.GetBytes(((processorCount - seedByteTakeDetermine.Next(0, processorCount)) + System.Environment.TickCount) + currentThreadId);
                }
            }

            toHashForSeed = Sha512Digest(toHashForSeed, 0, toHashForSeed.Length);
            toHashForSeed = MergeByteArrays(toHashForSeed, guidBytes);
            toHashForSeed = MergeByteArrays(toHashForSeed, BitConverter.GetBytes(currentThreadId));
            toHashForSeed = MergeByteArrays(toHashForSeed, BitConverter.GetBytes(DateTime.UtcNow.Ticks));
            toHashForSeed = MergeByteArrays(toHashForSeed, BitConverter.GetBytes(DateTime.Now.Ticks));
            toHashForSeed = MergeByteArrays(toHashForSeed, BitConverter.GetBytes(System.Environment.TickCount));
            toHashForSeed = MergeByteArrays(toHashForSeed, BitConverter.GetBytes(processorCount));
            toHashForSeed = MergeByteArrays(toHashForSeed, threadedSeedBytes);
            toHashForSeed = Sha512Digest(toHashForSeed, 0, toHashForSeed.Length);

            //we grab a random amount of bytes between 24 and 64 to rehash  make a new set of 64 bytes, using guidBytes as hmackey
            toHashForSeed = Sha512Digest(HmacSha512Digest(toHashForSeed, 0, seedByteTakeDetermine.Next(24, 64), guidBytes), 0, 64);

            seedByteTakeDetermine.SetSeed(currentThreadId + (DateTime.Now.Ticks - System.Environment.TickCount));

            //by making the iterations also random we are again making it hard to determin our seed by brute force
            int iterations = seedStretchingIterations - (seedByteTakeDetermine.Next(0, (seedStretchingIterations / seedByteTakeDetermine.Next(9, 100))));

            //here we use key stretching techniques to make it harder to replay the random seed values by forcing computational time up
            byte[] seedMaterial = Rfc2898_pbkdf2_hmacsha512.PBKDF2(toHashForSeed, seedByteTakeDetermine.GenerateSeed(64), iterations);

            //build a SecureRandom object that uses Sha512 to provide randomness and we will give it our created above hardened seed
            SecureRandom secRand = new SecureRandom(new Org.BouncyCastle.Crypto.Prng.DigestRandomGenerator(new Sha512Digest()));

            //set the seed that we created just above
            secRand.SetSeed(seedMaterial);

            //generate more seed materisal
            secRand.SetSeed(currentThreadId);
            secRand.SetSeed(MergeByteArrays(guidBytes, threadedSeedBytes));
            secRand.SetSeed(secRand.GenerateSeed(1 + secRand.Next(64)));

            //add our prefab seed again onto the previous material just to be sure the above statements are adding and not clobbering seed material
            secRand.SetSeed(seedMaterial);

            //here we derive our random bytes
            secRand.NextBytes(output, 0, size);

            return(output);
        }
Пример #5
0
        private void RandomTest(SecureRandom random)
        {
            int kLength = 32;

            byte[] K = new byte[kLength];
            random.NextBytes(K);

            int pHead   = random.Next(256);
            int pLength = random.Next(65536);
            int pTail   = random.Next(256);

            byte[] P = new byte[pHead + pLength + pTail];
            random.NextBytes(P);

            int aLength = random.Next(256);

            byte[] A = new byte[aLength];
            random.NextBytes(A);

            int saLength = random.Next(256);

            byte[] SA = new byte[saLength];
            random.NextBytes(SA);

            int nonceLength = 12;

            byte[] nonce = new byte[nonceLength];
            random.NextBytes(nonce);

            AeadParameters   parameters = new AeadParameters(new KeyParameter(K), 16 * 8, nonce, A);
            ChaCha20Poly1305 cipher     = InitCipher(true, parameters);

            int ctLength = cipher.GetOutputSize(pLength);

            byte[] C = new byte[saLength + ctLength];
            Array.Copy(SA, 0, C, 0, saLength);

            int split = NextInt(random, saLength + 1);

            cipher.ProcessAadBytes(C, 0, split);
            cipher.ProcessAadBytes(C, split, saLength - split);

            int predicted = cipher.GetUpdateOutputSize(pLength);
            int len       = cipher.ProcessBytes(P, pHead, pLength, C, saLength);

            if (predicted != len)
            {
                Fail("encryption reported incorrect update length in randomised test");
            }

            len += cipher.DoFinal(C, saLength + len);
            if (ctLength != len)
            {
                Fail("encryption reported incorrect length in randomised test");
            }

            byte[] encT = cipher.GetMac();
            byte[] tail = new byte[ctLength - pLength];
            Array.Copy(C, saLength + pLength, tail, 0, tail.Length);

            if (!AreEqual(encT, tail))
            {
                Fail("stream contained wrong mac in randomised test");
            }

            cipher.Init(false, parameters);

            int decPHead   = random.Next(256);
            int decPLength = cipher.GetOutputSize(ctLength);
            int decPTail   = random.Next(256);

            byte[] decP = new byte[decPHead + decPLength + decPTail];

            split = NextInt(random, saLength + 1);
            cipher.ProcessAadBytes(C, 0, split);
            cipher.ProcessAadBytes(C, split, saLength - split);

            predicted = cipher.GetUpdateOutputSize(ctLength);
            len       = cipher.ProcessBytes(C, saLength, ctLength, decP, decPHead);
            if (predicted != len)
            {
                Fail("decryption reported incorrect update length in randomised test");
            }

            len += cipher.DoFinal(decP, decPHead + len);

            if (!AreEqual(P, pHead, pHead + pLength, decP, decPHead, decPHead + decPLength))
            {
                Fail("incorrect decrypt in randomised test");
            }

            byte[] decT = cipher.GetMac();
            if (!AreEqual(encT, decT))
            {
                Fail("decryption produced different mac from encryption");
            }

            //
            // key reuse test
            //
            cipher.Init(false, AeadTestUtilities.ReuseKey(parameters));

            decPHead   = random.Next(256);
            decPLength = cipher.GetOutputSize(ctLength);
            decPTail   = random.Next(256);
            decP       = new byte[decPHead + decPLength + decPTail];

            split = NextInt(random, saLength + 1);
            cipher.ProcessAadBytes(C, 0, split);
            cipher.ProcessAadBytes(C, split, saLength - split);

            len  = cipher.ProcessBytes(C, saLength, ctLength, decP, decPHead);
            len += cipher.DoFinal(decP, decPHead + len);

            if (!AreEqual(P, pHead, pHead + pLength, decP, decPHead, decPHead + decPLength))
            {
                Fail("incorrect decrypt in randomised test");
            }

            decT = cipher.GetMac();
            if (!AreEqual(encT, decT))
            {
                Fail("decryption produced different mac from encryption");
            }
        }
Пример #6
0
        public async Task UseCapsuleReq(GameSession session, ItemUseCapsuleReqMessage message)
        {
            var item = session.Player.Inventory.GetItem(message.ItemId);

            if (item.ItemNumber.Id == 4030051) //capsule
            {
                var  random = new SecureRandom();
                uint count  = 100;
                for (var i = 0; i < 5; i++)
                {
                    var counta = (uint)random.Next(1, 100);
                    if (counta < count)
                    {
                        count = counta;
                    }
                }

                if (count >= 75)
                {
                    count = 100;
                }
                else if (count >= 50)
                {
                    count = 50;
                }
                else if (count >= 25)
                {
                    count = 25;
                }
                else if (count >= 20)
                {
                    count = 20;
                }
                else if (count >= 15)
                {
                    count = 15;
                }
                else if (count >= 5)
                {
                    count = 5;
                }
                else if (count >= 2)
                {
                    count = 2;
                }
                else if (count >= 1)
                {
                    count = 1;
                }


                var pencount = 0;
                pencount = random.Next(300, (int)(count + 300 * 100));
                pencount = 5 * (int)Math.Round(pencount / 5.0);
                pencount = 150 * (int)Math.Round(pencount / 150.0);

                var reward = new List <CapsuleRewardDto>
                {
                    new CapsuleRewardDto(CapsuleRewardType.Item, 0, new ItemNumber(6000001), ItemPriceType.CP,
                                         ItemPeriodType.Units, count),
                    new CapsuleRewardDto(CapsuleRewardType.PEN, (uint)pencount, new ItemNumber(),
                                         ItemPriceType.PEN, ItemPeriodType.None, 0)
                };

                await session.SendAsync(new ItemUseCapsuleAckMessage(reward.ToArray(), 3));

                if (item.Count <= 1)
                {
                    session.Player.Inventory.Remove(item);
                }
                else
                {
                    item.Count      -= 1;
                    item.NeedsToSave = true;
                    await session.SendAsync(new ItemUpdateInventoryAckMessage(InventoryAction.Update,
                                                                              item.Map <PlayerItem, ItemDto>()));
                }
            }
            else
            {
                await session.SendAsync(new ItemUseCapsuleAckMessage(1));
            }
        }
Пример #7
0
        private ITestResult KeyWrapTests()
        {
            //KW mode (PADDING NOT SUPPORTED)
            //test 1

            /*
             * Initial implementation had bugs handling offset and length correctly, so for
             * this first test case we embed the input inside a larger buffer.
             */
            byte[] textA      = SecureRandom.GetNextBytes(Random, Random.Next(1, 64));
            byte[] textB      = SecureRandom.GetNextBytes(Random, Random.Next(1, 64));
            byte[] textToWrap = Arrays.ConcatenateAll(textA, Hex.Decode("101112131415161718191A1B1C1D1E1F"), textB);

            byte[] key = Hex.Decode("000102030405060708090A0B0C0D0E0F");
            byte[] expectedWrappedText = Hex.Decode("1DC91DC6E52575F6DBED25ADDA95A1B6AD3E15056E489738972C199FB9EE2913");
            byte[] output = new byte[expectedWrappedText.Length];

            Dstu7624WrapEngine wrapper = new Dstu7624WrapEngine(128);

            wrapper.Init(true, new KeyParameter(key));
            output = wrapper.Wrap(textToWrap, textA.Length, textToWrap.Length - textA.Length - textB.Length);

            if (!Arrays.AreEqual(output, expectedWrappedText))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 1 - expected "
                                            + Hex.ToHexString(expectedWrappedText)
                                            + " got " + Hex.ToHexString(output)));
            }

            output = Arrays.ConcatenateAll(textB, output, textA);

            wrapper.Init(false, new KeyParameter(key));
            output = wrapper.Unwrap(output, textB.Length, output.Length - textB.Length - textA.Length);

            byte[] expected = Arrays.CopyOfRange(textToWrap, textA.Length, textToWrap.Length - textB.Length);
            if (!Arrays.AreEqual(output, expected))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 1 - expected "
                                            + Hex.ToHexString(expected)
                                            + " got " + Hex.ToHexString(output)));
            }

            //test 2
            key                 = Hex.Decode("000102030405060708090A0B0C0D0E0F");
            textToWrap          = Hex.Decode("101112131415161718191A1B1C1D1E1F20219000000000000000800000000000");
            expectedWrappedText = Hex.Decode("0EA983D6CE48484D51462C32CC61672210FCC44196ABE635BAF878FDB83E1A63114128585D49DB355C5819FD38039169");

            output = new byte[expectedWrappedText.Length];

            wrapper.Init(true, new KeyParameter(key));
            output = wrapper.Wrap(textToWrap, 0, textToWrap.Length);


            if (!Arrays.AreEqual(output, expectedWrappedText))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 2 - expected "
                                            + Hex.ToHexString(expectedWrappedText)
                                            + " got " + Hex.ToHexString(output)));
            }


            wrapper.Init(false, new KeyParameter(key));
            output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length);

            if (!Arrays.AreEqual(output, textToWrap))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 2 - expected "
                                            + Hex.ToHexString(textToWrap)
                                            + " got " + Hex.ToHexString(output)));
            }


            //test 3
            key                 = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F");
            textToWrap          = Hex.Decode("202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F");
            expectedWrappedText = Hex.Decode("2D09A7C18E6A5A0816331EC27CEA596903F77EC8D63F3BDB73299DE7FD9F4558E05992B0B24B39E02EA496368E0841CC1E3FA44556A3048C5A6E9E335717D17D");

            output = new byte[expectedWrappedText.Length];

            wrapper = new Dstu7624WrapEngine(128);
            wrapper.Init(true, new KeyParameter(key));
            output = wrapper.Wrap(textToWrap, 0, textToWrap.Length);


            if (!Arrays.AreEqual(output, expectedWrappedText))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 3 - expected "
                                            + Hex.ToHexString(expectedWrappedText)
                                            + " got " + Hex.ToHexString(output)));
            }

            wrapper.Init(false, new KeyParameter(key));
            output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length);

            if (!Arrays.AreEqual(output, textToWrap))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 3 - expected "
                                            + Hex.ToHexString(textToWrap)
                                            + " got " + Hex.ToHexString(output)));
            }

            //test 4
            key                 = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F");
            textToWrap          = Hex.Decode("202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464E8040000000000020");
            expectedWrappedText = Hex.Decode("37E3EECB91150C6FA04CFD19D6FC57B7168C9FA5C5ED18601C68EE4AFD7301F8C8C51D7A0A5CD34F6FAB0D8AF11845CC1E4B16E0489FDA1D76BA4EFCFD161F76");

            output = new byte[expectedWrappedText.Length];

            wrapper = new Dstu7624WrapEngine(128);
            wrapper.Init(true, new KeyParameter(key));
            output = wrapper.Wrap(textToWrap, 0, textToWrap.Length);


            if (!Arrays.AreEqual(output, expectedWrappedText))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 4 - expected "
                                            + Hex.ToHexString(expectedWrappedText)
                                            + " got " + Hex.ToHexString(output)));
            }

            wrapper.Init(false, new KeyParameter(key));
            output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length);

            if (!Arrays.AreEqual(output, textToWrap))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 4 - expected "
                                            + Hex.ToHexString(textToWrap)
                                            + " got " + Hex.ToHexString(output)));
            }

            //test 5
            key                 = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F");
            textToWrap          = Hex.Decode("202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F");
            expectedWrappedText = Hex.Decode("BE59D3C3C31B2685A8FA57CD000727F16AF303F0D87BC2D7ABD80DC2796BBC4CDBC4E0408943AF4DAF7DE9084DC81BFEF15FDCDD0DF399983DF69BF730D7AE2A199CA4F878E4723B7171DD4D1E8DF59C0F25FA0C20946BA64F9037D724BB1D50B6C2BD9788B2AF83EF6163087CD2D4488BC19F3A858D813E3A8947A529B6D65D");

            output = new byte[expectedWrappedText.Length];

            wrapper = new Dstu7624WrapEngine(256);
            wrapper.Init(true, new KeyParameter(key));
            output = wrapper.Wrap(textToWrap, 0, textToWrap.Length);


            if (!Arrays.AreEqual(output, expectedWrappedText))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 5 - expected "
                                            + Hex.ToHexString(expectedWrappedText)
                                            + " got " + Hex.ToHexString(output)));
            }

            wrapper.Init(false, new KeyParameter(key));
            output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length);

            if (!Arrays.AreEqual(output, textToWrap))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 5 - expected "
                                            + Hex.ToHexString(textToWrap)
                                            + " got " + Hex.ToHexString(output)));
            }


            //test 6
            key                 = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F");
            textToWrap          = Hex.Decode("202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F708802000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000");
            expectedWrappedText = Hex.Decode("CC41D643B08592F509432E3C6F4B73156907A53B9FFB99B157DEC708F917AEA1E41D76475EDFB138A8B0220A152B673E9713DE7A2791E3573FE257C3FF3C0DAA9AD13477E52770F54CBF94D1603AED7CA876FB7913BC359D2B89562299FA92D32A9C17DBE4CC21CCE097089B9FBC245580D6DB59F8731D864B604E654397E5F5E7A79A6A777C75856039C8C86140D0CB359CA3923D902D08269F8D48E7F0F085");

            output = new byte[expectedWrappedText.Length];

            wrapper = new Dstu7624WrapEngine(256);
            wrapper.Init(true, new KeyParameter(key));
            output = wrapper.Wrap(textToWrap, 0, textToWrap.Length);


            if (!Arrays.AreEqual(output, expectedWrappedText))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 6 - expected "
                                            + Hex.ToHexString(expectedWrappedText)
                                            + " got " + Hex.ToHexString(output)));
            }

            wrapper.Init(false, new KeyParameter(key));
            output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length);

            if (!Arrays.AreEqual(output, textToWrap))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 6 - expected "
                                            + Hex.ToHexString(textToWrap)
                                            + " got " + Hex.ToHexString(output)));
            }


            //test 7
            key                 = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F");
            textToWrap          = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F");
            expectedWrappedText = Hex.Decode("599217EB2B5270ECEF0BB716D70E251234A2451CE04FCFBAEEA92022C581F19B7C9386BB7476B4AD721D40778F49062C3605F1E8FAC9F3F3AC04E46E89E1844DBF4F18FA9303B288741ABD71013CF208F31B4C76FBE342F89B1ABFD97E830457555651B74D3CCDBF94CC5E5EEC22821536A96F44C8BC4346B0271303E67FD313");

            output = new byte[expectedWrappedText.Length];

            wrapper = new Dstu7624WrapEngine(256);
            wrapper.Init(true, new KeyParameter(key));
            output = wrapper.Wrap(textToWrap, 0, textToWrap.Length);


            if (!Arrays.AreEqual(output, expectedWrappedText))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 7 - expected "
                                            + Hex.ToHexString(expectedWrappedText)
                                            + " got " + Hex.ToHexString(output)));
            }

            wrapper.Init(false, new KeyParameter(key));
            output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length);

            if (!Arrays.AreEqual(output, textToWrap))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 7 - expected "
                                            + Hex.ToHexString(textToWrap)
                                            + " got " + Hex.ToHexString(output)));
            }

            //test 8
            key                 = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F");
            textToWrap          = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F908802000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000");
            expectedWrappedText = Hex.Decode("B92E58F53C38F7D23F1068FA98B921AC800AD0D1947BD620700D0B6088F87D03D6A516F54198154D0C71169C2BCF520F3DF3DF527FC23E800E9A65158D45BB253A3BD0493E4822DF0DB5A366BC2F47551C5D477DDDE724A0B869F562223CEDB9D4AA36C750FA864ADF938273FBC859F7D4930F6B70C6474304AB670BA32CB0C41023769338A29EA1555F526CDFEB75C72212CD2D29F4BA49C2A62ACBE4F3272B");

            output = new byte[expectedWrappedText.Length];

            wrapper = new Dstu7624WrapEngine(256);
            wrapper.Init(true, new KeyParameter(key));
            output = wrapper.Wrap(textToWrap, 0, textToWrap.Length);


            if (!Arrays.AreEqual(output, expectedWrappedText))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 8 - expected "
                                            + Hex.ToHexString(expectedWrappedText)
                                            + " got " + Hex.ToHexString(output)));
            }

            wrapper.Init(false, new KeyParameter(key));
            output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length);

            if (!Arrays.AreEqual(output, textToWrap))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 8 - expected "
                                            + Hex.ToHexString(textToWrap)
                                            + " got " + Hex.ToHexString(output)));
            }

            //test 9
            key                 = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F");
            textToWrap          = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF");
            expectedWrappedText = Hex.Decode("9618AE6065069D5054464040F17337D58BEB51AE92391D740BDF7ABB239709C46270832039FF045BCF7878E7DA9C3B4CF89326CA8B4D29DB8680EEAE1B5A18463284713A323A69AEBF33CFC4B11283C7C8041FFC97668EDF727823411C9559816C108C11EC401643765527860D8DA0ED7254792C21DB775DEB1D6971C924CC83EB626173D894694943B1828ABDE8F9495BCEBA9AC3A4A03592C085AA29CC9A0C65786E631A702D589B819C89E79EEFF29C4EC312C8860BB68F02272EA770FB8D");

            output = new byte[expectedWrappedText.Length];

            wrapper = new Dstu7624WrapEngine(512);
            wrapper.Init(true, new KeyParameter(key));
            output = wrapper.Wrap(textToWrap, 0, textToWrap.Length);


            if (!Arrays.AreEqual(output, expectedWrappedText))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 9 - expected "
                                            + Hex.ToHexString(expectedWrappedText)
                                            + " got " + Hex.ToHexString(output)));
            }

            wrapper.Init(false, new KeyParameter(key));
            output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length);

            if (!Arrays.AreEqual(output, textToWrap))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 9 - expected "
                                            + Hex.ToHexString(textToWrap)
                                            + " got " + Hex.ToHexString(output)));
            }


            //test 10
            key                 = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F");
            textToWrap          = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE00805000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
            expectedWrappedText = Hex.Decode("3A05BB41513555F171E9234D4834EDAD16C0BAA6136197650138219C5DA406A703C39259E9DCCF6F2691EC691CE7414B5D3CDA006DE6D6C62142FAAA742C5F8AF64FCE95BE7ABA7FE5E06C3C33EE67BAEAB196E3A71132CAE78CD605A22E34D53CD159217E7B692CC79FAC66BF5E08DBC4FE274299474E176DDDF9F462AC63F4872E9B7F16B98AA56707EE5F2F94616CFC6A9548ADBD7DCB73664C331213964593F712ECCDFA7A94E3ABA7995176EA4B7E77096A3A3FF4E4087F430B62D5DEE64999F235FA9EAC79896A1C2258BF1DFC8A6AD0E5E7E06EAEEA0CCC2DEF62F67ECE8D12EFF432277C40A7BF1A23440B3533AF1E2F7AE1BBC076D12628BB4BC7B2E4D4B4353BCEAF9A67276B3FA23CADCA80062B95EBB2D51510AFA16F97249DF98E7B845C9A410F24B3C8B3E838E58D22BC2D14F46190FC1BFDB60C9691404F99");

            output = new byte[expectedWrappedText.Length];

            wrapper = new Dstu7624WrapEngine(512);
            wrapper.Init(true, new KeyParameter(key));
            output = wrapper.Wrap(textToWrap, 0, textToWrap.Length);


            if (!Arrays.AreEqual(output, expectedWrappedText))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 10 - expected "
                                            + Hex.ToHexString(expectedWrappedText)
                                            + " got " + Hex.ToHexString(output)));
            }

            wrapper.Init(false, new KeyParameter(key));
            output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length);

            if (!Arrays.AreEqual(output, textToWrap))
            {
                return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 10 - expected "
                                            + Hex.ToHexString(textToWrap)
                                            + " got " + Hex.ToHexString(output)));
            }

            return(new SimpleTestResult(true, Name + ": Okay"));
        }
Пример #8
0
        private int[,] GenerateField()
        {
            int[,] field = new int[this.Rows, this.Cols];

            var r = new SecureRandom();

            for (int i = 0; i < this.Bombs; i++)
            {
                int x = r.Next(this.Rows);
                int y = r.Next(this.Cols);
                if (field[x, y] == -1)
                {
                    i--;
                    continue;
                }
                field[x, y] = -1;
            }

            for (int i = 0; i < this.Rows; i++)
            {
                for (int j = 0; j < this.Cols; j++)
                {
                    if (field[i, j] == -1)
                    {
                        continue;
                    }

                    int count = 0;
                    if (i > 0 && j > 0 && field[i - 1, j - 1] == -1)
                    {
                        count++;
                    }
                    if (i > 0 && field[i - 1, j] == -1)
                    {
                        count++;
                    }
                    if (i > 0 && j < this.Cols - 1 && field[i - 1, j + 1] == -1)
                    {
                        count++;
                    }
                    if (j > 0 && field[i, j - 1] == -1)
                    {
                        count++;
                    }
                    if (j < this.Cols - 1 && field[i, j + 1] == -1)
                    {
                        count++;
                    }
                    if (i < this.Rows - 1 && j > 0 && field[i + 1, j - 1] == -1)
                    {
                        count++;
                    }
                    if (i < this.Rows - 1 && field[i + 1, j] == -1)
                    {
                        count++;
                    }
                    if (i < this.Rows - 1 && j < this.Cols - 1 && field[i + 1, j + 1] == -1)
                    {
                        count++;
                    }

                    field[i, j] = count;
                }
            }

            return(field);
        }
Пример #9
0
        public String GeneratePassword(CombinedKeyOptions options)
        {
            if ((options.PassphraseGenerationOptions == null || options.PassphraseGenerationOptions.WordCount == 0) &&
                (options.PasswordGenerationOptions == null || options.PasswordGenerationOptions.Length == 0))
            {
                throw new Exception("Bad options");
            }

            string key = "";

            Random random = new SecureRandom();

            var passwordOptions   = options.PasswordGenerationOptions;
            var passphraseOptions = options.PassphraseGenerationOptions;

            if (passphraseOptions != null && passphraseOptions.WordCount > 0)
            {
                var    wl         = new Wordlist();
                string passphrase = "";
                for (int i = 0; i < passphraseOptions.WordCount; i++)
                {
                    string word = wl.GetWord(random);

                    if (passphraseOptions.CaseMode == PassphraseGenerationOptions.PassphraseCaseMode.Uppercase)
                    {
                        word = word.ToUpper();
                    }
                    else if (passphraseOptions.CaseMode == PassphraseGenerationOptions.PassphraseCaseMode.Lowercase)
                    {
                        word = word.ToLower();
                    }
                    else if (passphraseOptions.CaseMode == PassphraseGenerationOptions.PassphraseCaseMode.PascalCase)
                    {
                        word = word.ToUpperFirstLetter();
                    }

                    passphrase += word;

                    if (i < passphraseOptions.WordCount - 1 || passwordOptions != null)
                    {
                        passphrase += passphraseOptions.Separator;
                    }
                }

                key += passphrase;
            }


            if (passwordOptions != null)
            {
                var    groups       = GetCharacterGroups(passwordOptions);
                String characterSet = GetCharacterSet(passwordOptions, groups);

                if (characterSet.Length == 0)
                {
                    throw new Exception("Bad options");
                }

                int size = characterSet.Length;

                StringBuilder buffer = new StringBuilder();

                if (passwordOptions.AtLeastOneFromEachGroup)
                {
                    foreach (var g in groups)
                    {
                        if (g.Length > 0)
                        {
                            buffer.Append(g[random.Next(g.Length)]);
                        }
                    }
                }

                if (size > 0)
                {
                    while (buffer.Length < passwordOptions.Length)
                    {
                        buffer.Append(characterSet[random.Next(size)]);
                    }
                }

                var password = buffer.ToString();

                if (passwordOptions.AtLeastOneFromEachGroup)
                {
                    //shuffle
                    StringBuilder sb = new StringBuilder(password);
                    for (int i = (password.Length - 1); i >= 1; i--)
                    {
                        int j = random.Next(i + 1);

                        var tmp = sb[i];
                        sb[i] = sb[j];
                        sb[j] = tmp;
                    }

                    password = sb.ToString();
                }

                key += password;
            }


            return(key);
        }
Пример #10
0
 public static string makeGUID(object paramObject)
 {
     return(hexFormat((int)DateTimeHelper.CurrentUnixTimeMillis() & 0xFFFFFF) + getUUIDMiddleValue(paramObject) + hexFormat(s_rand.Next()));
 }
Пример #11
0
        public void IntInRangeTest()
        {
            var nextD = _random.Next(0, 10);

            Assert.AreNotEqual(0.0, nextD);
        }
        public async Task <List <string> > TransferRandomAmounts(Web3.Web3 web3, Account fromAccount, BigInteger amount,
                                                                 params Account[] accounts)
        {
            var transfers = new List <string>();
            var ethAmount = Web3.Web3.Convert.FromWei(amount);

            //limited to accounts that have at least 1 Ether per account distribution
            if (Decimal.Truncate(ethAmount) > accounts.Length)
            {
                var        secureRandom           = new SecureRandom();
                BigInteger totalAmountDistributed = 0;
                string     lastTransaction        = null;


                for (int i = 0; i < accounts.Length; i++)
                {
                    BigInteger currentAmount = 0;
                    if (i == accounts.Length - 1)
                    {
                        if (lastTransaction != null)
                        {
                            var receipt = await PollForReceiptAsync(web3, lastTransaction, 15000);
                        }
                        currentAmount = await web3.Eth.GetBalance.SendRequestAsync(fromAccount.Address);

                        currentAmount = currentAmount - (web3.TransactionManager.DefaultGas * web3.TransactionManager.DefaultGasPrice);
                    }
                    else
                    {
                        currentAmount = 0;
                        while (currentAmount == 0)
                        {
                            var percentage       = secureRandom.Next(100 / accounts.Length - 1);
                            var percentageAmount = Decimal.Truncate(ethAmount * percentage / 100);

                            if (percentageAmount > 0)
                            {
                                currentAmount = Web3.Web3.Convert.ToWei(percentageAmount);
                            }
                        }
                        totalAmountDistributed = totalAmountDistributed + currentAmount;
                    }

                    var txn = await web3.Eth.TransactionManager.SendTransactionAsync(fromAccount.Address, accounts[i].Address, new HexBigInteger(currentAmount));

                    transfers.Add(txn);
                    lastTransaction = txn;

                    System.Console.WriteLine("Txn: " + txn + " Transferred to:" + accounts[i].Address + " Total: " + Web3.Web3.Convert.FromWei(currentAmount).ToString());
                }
            }
            else
            {
                //transfer it to the first account in the list if not enough ether to distribute all the amounts
                BigInteger currentAmount = 0;
                currentAmount = await web3.Eth.GetBalance.SendRequestAsync(fromAccount.Address);

                currentAmount = currentAmount - (web3.TransactionManager.DefaultGas * web3.TransactionManager.DefaultGasPrice);
                var txn = await web3.Eth.TransactionManager.SendTransactionAsync(fromAccount.Address, accounts[0].Address, new HexBigInteger(currentAmount));

                transfers.Add(txn);
            }

            return(transfers);
        }
Пример #13
0
        private void randomTest(
            SecureRandom srng,
            IGcmMultiplier m)
        {
            int kLength = 16 + 8 * srng.Next(3);

            byte[] K = new byte[kLength];
            srng.NextBytes(K);

            int pLength = srng.Next(1024);

            byte[] P = new byte[pLength];
            srng.NextBytes(P);

            int aLength = srng.Next(1024);

            byte[] A = new byte[aLength];
            srng.NextBytes(A);

            int ivLength = 1 + srng.Next(1024);

            byte[] IV = new byte[ivLength];
            srng.NextBytes(IV);

            GcmBlockCipher cipher     = new GcmBlockCipher(new AesFastEngine(), m);
            AeadParameters parameters = new AeadParameters(new KeyParameter(K), 16 * 8, IV, A);

            cipher.Init(true, parameters);
            byte[] C   = new byte[cipher.GetOutputSize(P.Length)];
            int    len = cipher.ProcessBytes(P, 0, P.Length, C, 0);

            len += cipher.DoFinal(C, len);

            if (C.Length != len)
            {
//				Console.WriteLine("" + C.Length + "/" + len);
                Fail("encryption reported incorrect length in randomised test");
            }

            byte[] encT = cipher.GetMac();
            byte[] tail = new byte[C.Length - P.Length];
            Array.Copy(C, P.Length, tail, 0, tail.Length);

            if (!AreEqual(encT, tail))
            {
                Fail("stream contained wrong mac in randomised test");
            }

            cipher.Init(false, parameters);
            byte[] decP = new byte[cipher.GetOutputSize(C.Length)];
            len  = cipher.ProcessBytes(C, 0, C.Length, decP, 0);
            len += cipher.DoFinal(decP, len);

            if (!AreEqual(P, decP))
            {
                Fail("incorrect decrypt in randomised test");
            }

            byte[] decT = cipher.GetMac();
            if (!AreEqual(encT, decT))
            {
                Fail("decryption produced different mac from encryption");
            }
        }
Пример #14
0
        public async Task <IActionResult> RequestCert(string reviewerUuid)
        {
            if (string.IsNullOrEmpty(reviewerUuid))
            {
                return(NotFound());
            }

            var reviewer = await DBContext.Reviewer
                           .SingleOrDefaultAsync(m => m.Uuid == reviewerUuid);

            if (reviewer == null)
            {
                return(NotFound());
            }

            var certificate = reviewer.Certificate;

            if (reviewer.Certificate != null)
            {
                if (reviewer.Certificate.Revoked != true && reviewer.Certificate.ExpireDate > DateTime.Now)
                {
                    return(RedirectToAction(nameof(CertificateExists)));
                }

                reviewer.Certificate.Revoked = true;
                DBContext.Certificate.Update(reviewer.Certificate);
                await DBContext.SaveChangesAsync();

                reviewer.Certificate = null;
                DBContext.Reviewer.Update(reviewer);
                await DBContext.SaveChangesAsync();
            }

            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);
            var request         = new CertificateRequest {
                Uuid         = Guid.NewGuid().ToString(),
                ReviewerUuid = reviewerUuid,
                Reviewer     = reviewer,
                RequestDate  = DateTime.Now,
                SecurityCode = random.Next(10000000, 99999999).ToString()
            };

            await DBContext.CertificateRequest.AddAsync(request);

            await DBContext.SaveChangesAsync();

            var message = await RenderService.RenderToStringAsync("Email/CertificateRequest", request);

            var response = await EmailManager.SendEmailHTML(
                message,
                EmailManager.Sender,
                reviewer.Email,
                "Certificate Request Confirmation",
                null);

            if (!response.Successful)
            {
                return(View("ErrorSendingRequest"));
            }

            return(View());
        }
Пример #15
0
 private Pocket GetRandomClient()
 {
     return(Datas.Pockets.ElementAt(secureRandom.Next(0, Settings.NumbersOfClients)));
 }
Пример #16
0
    private string CreateAccessId()
    {
        SecureRandom secureRandom = new SecureRandom();

        return(secureRandom.Next() + Guid.NewGuid().ToString());
    }
Пример #17
0
        public void HexTypeBasicUsageTest()
        {
            const int repeats = 100000;

            // 1. Number<T> <-> Hex  변환 테스트
            // 2. Number<T> <-> Hex <-> byte[] 변환 테스트
            // 3. Number<T> <-> Hex <-> string 변환 테스트

            // bool ( true, false )
            for (int i = 0; i < 2; i++)
            {
                // bool <-> Hex
                bool expected = (i % 2 == 0);
                Hex  hex      = expected;
                bool actual   = hex;
                Assert.Equal(expected, actual);

                // bool <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // bool <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // byte ( 0 ~ 255 )
            for (int i = byte.MinValue; i <= byte.MaxValue; i++)
            {
                // byte <-> Hex
                byte expected = (byte)i;
                Hex  hex      = expected;
                byte actual   = hex;
                Assert.Equal(expected, actual);

                // byte <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // byte <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // sbyte ( -128 ~ 127 )
            for (int i = sbyte.MinValue; i <= sbyte.MaxValue; i++)
            {
                // sbyte <-> Hex
                sbyte expected = (sbyte)i;
                Hex   hex      = expected;
                sbyte actual   = hex;
                Assert.Equal(expected, actual);

                // sbyte <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // sbyte <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // short ( -32768 ~ 32767 )
            for (int i = short.MinValue; i <= short.MaxValue; i++)
            {
                // short <-> Hex
                short expected = (short)i;
                Hex   hex      = expected;
                short actual   = hex;
                Assert.Equal(expected, actual);

                // short <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // short <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // ushort ( 0 ~ 65535 )
            for (int i = ushort.MinValue; i <= ushort.MaxValue; i++)
            {
                // ushort <-> Hex
                ushort expected = (ushort)i;
                Hex    hex      = expected;
                ushort actual   = hex;
                Assert.Equal(expected, actual);

                // ushort <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // ushort <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // int
            for (int i = 0; i < repeats; i++)
            {
                // int <-> Hex
                int expected = SecureRandom.Next <int>();
                Hex hex      = expected;
                int actual   = hex;
                Assert.Equal(expected, actual);

                // int <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // int <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // uint
            for (int i = 0; i < repeats; i++)
            {
                // uint <-> Hex
                uint expected = SecureRandom.Next <uint>();
                Hex  hex      = expected;
                uint actual   = hex;
                Assert.Equal(expected, actual);

                // uint <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // uint <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // long
            for (int i = 0; i < repeats; i++)
            {
                // long <-> Hex
                long expected = SecureRandom.Next <long>();
                Hex  hex      = expected;
                long actual   = hex;
                Assert.Equal(expected, actual);

                // long <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // long <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // ulong
            for (int i = 0; i < repeats; i++)
            {
                // ulong <-> Hex
                ulong expected = SecureRandom.Next <ulong>();
                Hex   hex      = expected;
                ulong actual   = hex;
                Assert.Equal(expected, actual);

                // ulong <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // ulong <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // float
            for (int i = 0; i < repeats; i++)
            {
                // float <-> Hex
                float expected = SecureRandom.Next <float>();
                Hex   hex      = expected;
                float actual   = hex;
                Assert.Equal(expected, actual);

                // float <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // float <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // double
            for (int i = 0; i < repeats; i++)
            {
                // double <-> Hex
                double expected = SecureRandom.Next <double>();
                Hex    hex      = expected;
                double actual   = hex;
                Assert.Equal(expected, actual);

                // double <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // double <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }

            // decimal
            for (int i = 0; i < repeats; i++)
            {
                // decimal <-> Hex
                decimal expected = SecureRandom.Next <decimal>();
                Hex     hex      = expected;
                decimal actual   = hex;
                Assert.Equal(expected, actual);

                // decimal <-> Hex <-> byte[]
                byte[] bytes    = hex;
                Hex    hexBytes = bytes;
                actual = hexBytes;
                Assert.Equal(expected, actual);

                // decimal <-> Hex <-> string
                string str       = hex;
                Hex    hexString = str;
                actual = hexString;
                Assert.Equal(expected, actual);
            }
        }
Пример #18
0
        public void GenerateIntegerAfterDisposing()
        {
            SecureRandom random = null;

            using (random = new SecureRandom())
            {
            }

            random.Next();
        }
Пример #19
0
 /// <summary>
 /// get random shufled array
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="array"></param>
 /// <returns></returns>
 public static IEnumerable <T> Shuffle <T>(this IEnumerable <T> enums)
 {
     return(IsNullOrEmpty(enums) ? enums : enums.OrderBy(x => SecureRandom.Next <int>()).ToArray());
 }
Пример #20
0
 public void GenerateIntegers()
 {
     using (var random = new SecureRandom())
     {
         for (var i = 0; i < 100000; i++)
         {
             var x = random.Next();
             Assert.IsTrue(x >= 0);
         }
     }
 }
Пример #21
0
 public static uint RandomUint()
 {
     return((uint)Rnd.Next());
 }
Пример #22
0
 public void GenerateIntegersWithInvalidMaxAndMinValues()
 {
     using (var random = new SecureRandom())
     {
         const int Max = -25;
         const int Min = 25;
         random.Next(Min, Max);
     }
 }
Пример #23
0
        /// <summary>
        /// İstenen özelliklerde rastgele metin üretmek için kullanılır. Üretilen bu metin şifre olarak da kullanılabilir.
        /// </summary>
        /// <param name="pCharacterType">İstenen metnin özelliği</param>
        /// <param name="pLength">İstenen metnin uzunluğu</param>
        /// <returns></returns>
        public static string GenerateRandomString(CharacterTypes pCharacterType, int pLength)
        {
            string pw     = string.Empty;
            int    length = pLength - 1;

            int rdNumber = 0;
            int minValue = 0;
            int maxValue = 0;

            int dMin  = 48;
            int dMax  = 57;
            int uLMin = 65;
            int uLMax = 90;
            int lLMin = 97;
            int lLMax = 122;

            var _scrRandom = new SecureRandom();

            do
            {
                switch (pCharacterType)
                {
                case CharacterTypes.OnlyDigits:
                    minValue = dMin;
                    maxValue = dMax;
                    rdNumber = _scrRandom.Next(minValue, maxValue);
                    break;

                case CharacterTypes.UpperLetters:
                    minValue = uLMin;
                    maxValue = uLMax;
                    rdNumber = _scrRandom.Next(minValue, maxValue);
                    break;

                case CharacterTypes.LowerLetters:
                    minValue = lLMin;
                    maxValue = lLMax;
                    rdNumber = _scrRandom.Next(minValue, maxValue);
                    break;

                case CharacterTypes.UpperLowerLetters:
                    minValue = uLMin;
                    maxValue = lLMax;
                    do
                    {
                        rdNumber = _scrRandom.Next(minValue, maxValue);
                    }while (!((rdNumber >= uLMin & rdNumber <= uLMax) | (rdNumber >= lLMin & rdNumber <= lLMax)));
                    break;

                case CharacterTypes.DigitLowerLetters:
                    minValue = dMin;
                    maxValue = lLMax;
                    do
                    {
                        rdNumber = _scrRandom.Next(minValue, maxValue);
                    }while (!((rdNumber >= dMin & rdNumber <= dMax) | (rdNumber >= lLMin & rdNumber <= lLMax)));
                    break;

                case CharacterTypes.DigitUpperLetters:
                    minValue = dMin;
                    maxValue = uLMax;
                    do
                    {
                        rdNumber = _scrRandom.Next(minValue, maxValue);
                    }while (!((rdNumber >= dMin & rdNumber <= dMax) | (rdNumber >= uLMin & rdNumber <= uLMax)));
                    break;

                case CharacterTypes.DigitUpperLowerLetters:
                    minValue = dMin;
                    maxValue = lLMax;
                    do
                    {
                        rdNumber = _scrRandom.Next(minValue, maxValue);
                    }while (!((rdNumber >= dMin & rdNumber <= dMax) | (rdNumber >= uLMin & rdNumber <= uLMax) | (rdNumber >= lLMin & rdNumber <= lLMax)));
                    break;
                }

                pw = string.Format("{0}{1}", pw, (char)rdNumber);
            } while (pw.Length <= length);

            return(pw);
        }
Пример #24
0
        public void GenerateIntegersWithMaxLimit()
        {
            using (var random = new SecureRandom())
            {
                const int Max = 25;

                for (var i = 0; i < 100000; i++)
                {
                    var x = random.Next(Max);
                    Assert.IsTrue(x >= 0);
                    Assert.IsTrue(x < Max);
                }
            }
        }
Пример #25
0
 /// <summary>
 /// Gets the next random <see langword="int"/> from the <see cref="SecureRandom"/>.
 /// </summary>
 /// <returns> The random <see langword="int"/>. </returns>
 public override int Next() => secureRandom.Next();
Пример #26
0
        public void GenerateIntegersWithPositiveMaxAndNegativeMinLimits()
        {
            using (var random = new SecureRandom())
            {
                const int Max = 25;
                const int Min = -15;

                for (var i = 0; i < 100000; i++)
                {
                    var x = random.Next(Min, Max);
                    Assert.IsTrue(x >= Min);
                    Assert.IsTrue(x < Max);
                }
            }
        }
Пример #27
0
        public void Backdoor()
        {
            var random = new SecureRandom();
            var curve  = CustomNamedCurves.GetByName("secp521r1");
            var gen    = new ECKeyPairGenerator("ECDSA");
            var G      = curve.G;
            var N      = curve.N;
            var paramz = new ECDomainParameters(curve.Curve, G, N);

            gen.Init(new ECKeyGenerationParameters(paramz, random));

            var kCalc = new RandomDsaKCalculator();             // kCalc generates random values [1, N-1]

            kCalc.Init(N, random);

            var attackersKeyPair = gen.GenerateKeyPair();

            var v = ((ECPrivateKeyParameters)attackersKeyPair.Private).D;        //attacker's private
            var V = G.Multiply(v);                                               //attackers public

            var usersKeyPair = gen.GenerateKeyPair();                            //user's public
            var D            = ((ECPrivateKeyParameters)usersKeyPair.Private).D; //user's private
            var Q            = ((ECPublicKeyParameters)usersKeyPair.Public).Q;   //user's public


            const string message1 = "First message to sign";
            var          m1       = new BigInteger(1, Hash(Encoding.UTF8.GetBytes(message1))); // hash of m1

            //Generate signature 1
            var k1 = kCalc.NextK();             // k1 is true random
            var signaturePoint1 = G.Multiply(k1).Normalize();

            //(r1, s1) - signature 1
            var r1 = signaturePoint1.AffineXCoord.ToBigInteger().Mod(N);
            var s1 = k1.ModInverse(N).Multiply(m1.Add(D.Multiply(r1)));


            //verify signature 1
            var w            = s1.ModInverse(N);
            var u1           = m1.Multiply(w).Mod(N);
            var u2           = r1.Multiply(w).Mod(N);
            var verifyPoint1 = ECAlgorithms.SumOfTwoMultiplies(G, u1, Q, u2).Normalize();

            var valid1 = verifyPoint1.AffineXCoord.ToBigInteger().Mod(N).Equals(r1);


            //Generate signature 2
            const string message2 = "Second message to sign";
            var          m2       = new BigInteger(1, Hash(Encoding.UTF8.GetBytes(message2))); // hash of m2

            //here we generate a,b,h,e < N using seed = hash(m2)
            kCalc.Init(N, new SecureRandom(new SeededGenerator(Hash(Encoding.UTF8.GetBytes(message2)))));

            var a = kCalc.NextK();
            var b = kCalc.NextK();
            var h = kCalc.NextK();
            var e = kCalc.NextK();

            //u,j - true random
            var u = (random.Next() % 2) == 1 ? BigInteger.One : BigInteger.Zero;
            var j = (random.Next() % 2) == 1 ? BigInteger.One : BigInteger.Zero;

            //compute hidden field element
            var Z = G.Multiply(k1).Multiply(a)
                    .Add(V.Multiply(k1).Multiply(b))
                    .Add(G.Multiply(h).Multiply(j))
                    .Add(V.Multiply(e).Multiply(u))
                    .Normalize();

            var zX = Z.AffineXCoord.ToBigInteger().ToByteArray();

            var hash            = Hash(zX);
            var k2              = new BigInteger(1, hash);
            var signaturePoint2 = G.Multiply(k2).Normalize();

            //(r2, s2) = signature 2
            var r2 = signaturePoint2.AffineXCoord.ToBigInteger().Mod(N);
            var s2 = k2.ModInverse(N).Multiply(m2.Add(D.Multiply(r2)));

            //verify signature 2

            w  = s2.ModInverse(N);
            u1 = m2.Multiply(w).Mod(N);
            u2 = r2.Multiply(w).Mod(N);
            var verifyPoint2 = ECAlgorithms.SumOfTwoMultiplies(G, u1, Q, u2).Normalize();

            var valid2 = verifyPoint2.AffineXCoord.ToBigInteger().Mod(N).Equals(r2);

            if (valid1 && valid2)
            {
                //compute user's private key
                var d = ExtractUsersPrivateKey(G, N, message1, message2, r1, s1, r2, s2, v, V, Q);
                Console.WriteLine("Ecdsa private key restored: {0}", d.Equals(D));
            }
            else
            {
                Console.WriteLine("Something's wrong");
            }
        }
Пример #28
0
        public void GenerateIntegersWithSameMaxAndMinLimits()
        {
            using (var random = new SecureRandom())
            {
                const int Max = 25;
                const int Min = 25;

                for (var i = 0; i < 100000; i++)
                {
                    Assert.IsTrue(random.Next(Min, Max) == Min);
                }
            }
        }
Пример #29
0
        public override void PerformTest()
        {
            Asn1InputStream aIn = new Asn1InputStream(longTagged);

            DerApplicationSpecific app = (DerApplicationSpecific)aIn.ReadObject();

            aIn = new Asn1InputStream(app.GetContents());

            app = (DerApplicationSpecific)aIn.ReadObject();

            aIn = new Asn1InputStream(app.GetContents());

            Asn1TaggedObject tagged = (Asn1TaggedObject)aIn.ReadObject();

            if (tagged.TagNo != 32)
            {
                Fail("unexpected tag value found - not 32");
            }

            tagged = (Asn1TaggedObject)Asn1Object.FromByteArray(tagged.GetEncoded());

            if (tagged.TagNo != 32)
            {
                Fail("unexpected tag value found on recode - not 32");
            }

            tagged = (Asn1TaggedObject)aIn.ReadObject();

            if (tagged.TagNo != 33)
            {
                Fail("unexpected tag value found - not 33");
            }

            tagged = (Asn1TaggedObject)Asn1Object.FromByteArray(tagged.GetEncoded());

            if (tagged.TagNo != 33)
            {
                Fail("unexpected tag value found on recode - not 33");
            }

            aIn = new Asn1InputStream(longAppSpecificTag);

            app = (DerApplicationSpecific)aIn.ReadObject();

            if (app.ApplicationTag != 97)
            {
                Fail("incorrect tag number read");
            }

            app = (DerApplicationSpecific)Asn1Object.FromByteArray(app.GetEncoded());

            if (app.ApplicationTag != 97)
            {
                Fail("incorrect tag number read on recode");
            }

            SecureRandom sr = new SecureRandom();

            for (int i = 0; i < 100; ++i)
            {
                int testTag = (sr.NextInt() & int.MaxValue) >> sr.Next(26);
                app = new DerApplicationSpecific(testTag, new byte[] { 1 });
                app = (DerApplicationSpecific)Asn1Object.FromByteArray(app.GetEncoded());

                if (app.ApplicationTag != testTag)
                {
                    Fail("incorrect tag number read on recode (random test value: " + testTag + ")");
                }
            }
        }
Пример #30
0
 public void GenerateIntegerWithNegativeUpperBound()
 {
     using (var random = new SecureRandom())
     {
         random.Next(-2);
     }
 }
        private void DoTestConsistency(Ed448.Algorithm algorithm, byte[] context)
        {
            Ed448KeyPairGenerator kpg = new Ed448KeyPairGenerator();

            kpg.Init(new Ed448KeyGenerationParameters(Random));

            AsymmetricCipherKeyPair   kp         = kpg.GenerateKeyPair();
            Ed448PrivateKeyParameters privateKey = (Ed448PrivateKeyParameters)kp.Private;
            Ed448PublicKeyParameters  publicKey  = (Ed448PublicKeyParameters)kp.Public;

            byte[] msg = new byte[Random.NextInt() & 255];
            Random.NextBytes(msg);

            ISigner signer = CreateSigner(algorithm, context);

            signer.Init(true, privateKey);
            signer.BlockUpdate(msg, 0, msg.Length);
            byte[] signature = signer.GenerateSignature();

            ISigner verifier = CreateSigner(algorithm, context);

            {
                verifier.Init(false, publicKey);
                verifier.BlockUpdate(msg, 0, msg.Length);
                bool shouldVerify = verifier.VerifySignature(signature);

                if (!shouldVerify)
                {
                    Fail("Ed448(" + algorithm + ") signature failed to verify");
                }
            }

            {
                byte[] wrongLengthSignature = Arrays.Append(signature, 0x00);

                verifier.Init(false, publicKey);
                verifier.BlockUpdate(msg, 0, msg.Length);
                bool shouldNotVerify = verifier.VerifySignature(wrongLengthSignature);

                if (shouldNotVerify)
                {
                    Fail("Ed448(" + algorithm + ") wrong length signature incorrectly verified");
                }
            }

            if (msg.Length > 0)
            {
                bool shouldNotVerify = verifier.VerifySignature(signature);

                if (shouldNotVerify)
                {
                    Fail("Ed448(" + algorithm + ") wrong length failure did not reset verifier");
                }
            }

            {
                byte[] badSignature = Arrays.Clone(signature);
                badSignature[Random.Next() % badSignature.Length] ^= (byte)(1 << (Random.NextInt() & 7));

                verifier.Init(false, publicKey);
                verifier.BlockUpdate(msg, 0, msg.Length);
                bool shouldNotVerify = verifier.VerifySignature(badSignature);

                if (shouldNotVerify)
                {
                    Fail("Ed448(" + algorithm + ") bad signature incorrectly verified");
                }
            }
        }
Пример #32
0
        public void GenerateIntegerWithUpperRangeAfterDisposing()
        {
            SecureRandom random = null;

            using (random = new SecureRandom())
            {
            }

            random.Next(2);
        }
Пример #33
0
        /// <summary>
        /// Generates a random passphrase that contains between 6 and 10 words using a <em>Diceware</em> method (<see href="https://www.eff.org/dice">EFF Dice-Generated Passphrases</see>).
        /// </summary>
        /// <returns>Random ASCII password createad using a <em>Diceware</em> method.</returns>
        public static string GeneratePassphrase(string dicewareWordsPath)
        {
            var    diceRollResult = 0;
            string passphrase;
            var    delimiter = GeneratePassphraseDelimiter();

            var csprng = new SecureRandom(new DigestRandomGenerator(new Sha256Digest()));

            csprng.SetSeed(DateTime.Now.Ticks); // TODO: is this a good seed value?

            var maxNumberOfWords = csprng.Next(6, 10);

            // Loop only repeats if the generated passphrase has low entropy; this loop will never repeat because for the minimum of 6 words passphrase will have a good entropy.
            while (true)
            {
                var    numberOfWords = 0;
                string index;
                passphrase = "";

                // Loop repeats until we create a passphrase with an appropriate number of words.
                do
                {
                    var numberExist = false;

                    // Loop is used if the resulting 5-digit number isn't in the list.
                    do
                    {
                        // five dice rolls
                        for (var i = 0; i < 5; ++i)
                        {
                            diceRollResult += csprng.Next(1, 7) * (int)Math.Pow(10, i);
                        }

                        index          = Convert.ToString(diceRollResult);
                        diceRollResult = 0;

                        // TODO: can this be optimized?
                        using (var file = new StreamReader(dicewareWordsPath))
                        {
                            string line = null;
                            while ((line = file.ReadLine()) != null)
                            {
                                if (line.Contains(index))
                                {
                                    passphrase += line.Split('\t')[1].Trim();
                                    numberOfWords++;
                                    numberExist = true;
                                    break;
                                }
                            }
                        }
                    } while (!numberExist);

                    // Add delimiter between words.
                    if (numberOfWords != maxNumberOfWords - 1)
                    {
                        passphrase += delimiter;
                    }
                } while (numberOfWords < maxNumberOfWords);


                if (PasswordAdvisor.IsPasswordStrong(passphrase, out _, true, maxNumberOfWords))
                {
                    break;
                }
            }

            return(passphrase);
        }
Пример #34
0
        public void NextChaser()
        {
            _chaserRoundTime  = Room.Players.Count < 4 ? TimeSpan.FromSeconds(60) : TimeSpan.FromSeconds(Room.Players.Count * 15);
            _chaserRoundTime += TimeSpan.FromSeconds(Chaser != null ? 3 : 6);

            var MaxRatio = 0.0f;

            // Candidates are selecteds based on total score and chaser count
            var ChaserCandidates = from plr in Room.TeamManager.PlayersPlaying
                                   let stats = GetRecord(plr)
                                               select new { Player = plr, Ratio = (stats.ChaserCount * 100.0f /** (1.0f - plr.GetChaserRate())*/) + stats.TotalScore };

            foreach (var candidate in ChaserCandidates)
            {
                MaxRatio = candidate.Ratio > MaxRatio ? MaxRatio : candidate.Ratio;
            }

            _chaserTimer = TimeSpan.Zero;

            // Limit max trys to get a new chaser, prevent get stuck
            var _newChaserFounded = false;

            for (var trys = 0; trys < 10; trys++)
            {
                var index     = _random.Next(0, (int)MaxRatio);
                var candidate = ChaserCandidates.FirstOrDefault(plr => plr.Ratio <= index);
                if (candidate == null)
                {
                    continue;
                }

                Chaser = candidate.Player;
                break;
            }

            if (!_newChaserFounded)
            {
                var index = _random.Next(0, ChaserCandidates.Count());
                Chaser = ChaserCandidates.ElementAt(index).Player;
            }

            foreach (var plr in Room.TeamManager.PlayersPlaying)
            {
                plr.RoomInfo.State = PlayerState.Alive;
                if (plr != Chaser)
                {
                    GetStats(plr).ChaserRounds++;
                }
            }

            GetRecord(Chaser).ChaserCount++;
            GetStats(Chaser).ChasedRounds++;

            NextTarget();
            Room.Broadcast(new SlaughterChangeSlaughterAckMessage(
                               Chaser.Account.Id,
                               Room.TeamManager.PlayersPlaying
                               .Where(plr => plr != Chaser)
                               .Select(plr => plr.Account.Id).ToArray()
                               ));
            _waitingNextChaser = false;
        }
Пример #35
0
        private void RandomTest(SecureRandom srng, IGcmMultiplier m)
        {
            int kLength = 16 + 8 * srng.Next(3);

            byte[] K = new byte[kLength];
            srng.NextBytes(K);

            int pLength = srng.Next(65536);

            byte[] P = new byte[pLength];
            srng.NextBytes(P);

            int aLength = srng.Next(256);

            byte[] A = new byte[aLength];
            srng.NextBytes(A);

            int saLength = srng.Next(256);

            byte[] SA = new byte[saLength];
            srng.NextBytes(SA);

            int ivLength = 1 + srng.Next(256);

            byte[] IV = new byte[ivLength];
            srng.NextBytes(IV);

            AeadParameters parameters = new AeadParameters(new KeyParameter(K), 16 * 8, IV, A);
            GcmBlockCipher cipher     = InitCipher(m, true, parameters);

            byte[] C         = new byte[cipher.GetOutputSize(P.Length)];
            int    predicted = cipher.GetUpdateOutputSize(P.Length);

            int split = srng.Next(SA.Length + 1);

            cipher.ProcessAadBytes(SA, 0, split);
            int len = cipher.ProcessBytes(P, 0, P.Length, C, 0);

            cipher.ProcessAadBytes(SA, split, SA.Length - split);

            if (predicted != len)
            {
                Fail("encryption reported incorrect update length in randomised test");
            }

            len += cipher.DoFinal(C, len);

            if (C.Length != len)
            {
                Fail("encryption reported incorrect length in randomised test");
            }

            byte[] encT = cipher.GetMac();
            byte[] tail = new byte[C.Length - P.Length];
            Array.Copy(C, P.Length, tail, 0, tail.Length);

            if (!AreEqual(encT, tail))
            {
                Fail("stream contained wrong mac in randomised test");
            }

            cipher.Init(false, parameters);
            byte[] decP = new byte[cipher.GetOutputSize(C.Length)];
            predicted = cipher.GetUpdateOutputSize(C.Length);

            split = srng.Next(SA.Length + 1);
            cipher.ProcessAadBytes(SA, 0, split);
            len = cipher.ProcessBytes(C, 0, C.Length, decP, 0);
            cipher.ProcessAadBytes(SA, split, SA.Length - split);

            if (predicted != len)
            {
                Fail("decryption reported incorrect update length in randomised test");
            }

            len += cipher.DoFinal(decP, len);

            if (!AreEqual(P, decP))
            {
                Fail("incorrect decrypt in randomised test");
            }

            byte[] decT = cipher.GetMac();
            if (!AreEqual(encT, decT))
            {
                Fail("decryption produced different mac from encryption");
            }

            //
            // key reuse test
            //
            cipher.Init(false, AeadTestUtilities.ReuseKey(parameters));
            decP = new byte[cipher.GetOutputSize(C.Length)];

            split = NextInt(srng, SA.Length + 1);
            cipher.ProcessAadBytes(SA, 0, split);
            len = cipher.ProcessBytes(C, 0, C.Length, decP, 0);
            cipher.ProcessAadBytes(SA, split, SA.Length - split);

            len += cipher.DoFinal(decP, len);

            if (!AreEqual(P, decP))
            {
                Fail("incorrect decrypt in randomised test");
            }

            decT = cipher.GetMac();
            if (!AreEqual(encT, decT))
            {
                Fail("decryption produced different mac from encryption");
            }
        }
Пример #36
0
        public ActionResult DoorPrizes(long?id, FormCollection values)
        {
            if (this.CurrentUser == null || !this.Security.IsUserInRole(CurrentUser, this.Config.CrewGroup))
            {
                return(View("NotAuthorized"));
            }

            if (!id.HasValue)
            {
                long eventId = 0;
                if (long.TryParse(values["Event"], out eventId))
                {
                    return(RedirectToAction("DoorPrizes", new { id = eventId }));
                }
                else
                {
                    return(RedirectToAction("DoorPrizes"));
                }
            }

            var action = values["Action"];

            if (action == "ADD")
            {
                var prize = new Prize()
                {
                    EventId = id.Value,
                    Name    = values["Value"],
                };

                this.Db.Prizes.InsertOnSubmit(prize);

                this.Db.SubmitChanges();
            }
            else if (action == "DEL")
            {
                long prizeId = 0;
                if (!long.TryParse(values["Value"], out prizeId))
                {
                    return(View("Error", new ErrorInfoModel
                    {
                        ErrorMessage = "Could not convert value passed into a PrizeId"
                    }));
                }

                var prize = this.Db.Prizes.Where(p => p.PrizeId == prizeId && p.EventId == id.Value).SingleOrDefault();

                if (prize == null)
                {
                    return(View("NotFound"));
                }

                if (prize.WinnerUserId.HasValue)
                {
                    return(View("Error", new ErrorInfoModel
                    {
                        ErrorMessage = "Could not delete the prize, because it has already been drawn."
                    }));
                }

                this.Db.Prizes.DeleteOnSubmit(prize);

                this.Db.SubmitChanges();
            }
            else if (action == "DRW")
            {
                long prizeId = 0;
                if (!long.TryParse(values["Value"], out prizeId))
                {
                    return(View("Error", new ErrorInfoModel
                    {
                        ErrorMessage = "Could not convert value passed into a PrizeId"
                    }));
                }

                var prize = this.Db.Prizes.Where(p => p.PrizeId == prizeId && p.EventId == id.Value).SingleOrDefault();

                if (prize == null)
                {
                    return(View("NotFound"));
                }

                if (prize.WinnerUserId != null)
                {
                    return(View("Error", new ErrorInfoModel
                    {
                        ErrorMessage = "Could not draw the prize, because it has already been drawn."
                    }));
                }

                var users = (from r in this.Db.Registrations
                             where r.EventID == id.Value
                             where r.IsCheckedIn
                             select r.UserID).ToList();

                var rand = new SecureRandom();

                var winnerUserId = users[rand.Next(users.Count)];

                prize.WinnerUserId = winnerUserId;

                this.Db.SubmitChanges();
            }
            else if (action == "RVK")
            {
                long prizeId = 0;
                if (!long.TryParse(values["Value"], out prizeId))
                {
                    return(View("Error", new ErrorInfoModel
                    {
                        ErrorMessage = "Could not convert value passed into a PrizeId"
                    }));
                }

                var prize = this.Db.Prizes.Where(p => p.PrizeId == prizeId && p.EventId == id.Value).SingleOrDefault();

                if (prize == null)
                {
                    return(View("NotFound"));
                }

                if (!prize.WinnerUserId.HasValue)
                {
                    return(View("Error", new ErrorInfoModel
                    {
                        ErrorMessage = "Could not revoke the prize, because it has not been drawn."
                    }));
                }

                prize.WinnerUserId = null;

                this.Db.SubmitChanges();
            }
            else
            {
                return(View("NotAvailable"));
            }

            return(RedirectToAction("DoorPrizes", new { id = id.Value }));
        }