Next() public method

public Next ( ) : int
return int
Esempio n. 1
0
        private void RandomTest(SecureRandom random)
        {
            byte[] key = new byte[16];
            random.NextBytes(key);

            int length = 1 + random.Next(1024);
            byte[] input = new byte[length];
            random.NextBytes(input);

            SipHash mac = new SipHash();
            mac.Init(new KeyParameter(key));

            UpdateMac(mac, input, UPDATE_BYTES);
            long result1 = mac.DoFinal();

            UpdateMac(mac, input, UPDATE_FULL);
            long result2 = mac.DoFinal();

            UpdateMac(mac, input, UPDATE_MIX);
            long result3 = mac.DoFinal();

            if (result1 != result2 || result1 != result3)
            {
                Fail("Inconsistent results in random test");
            }
        }
        private static SecureString GenerateNewMachineKey(int keySize)
        {
            var random = new SecureRandom();
            random.SetSeed(random.GenerateSeed(128));

            var machineKeyString = "";
            for (var x = 0; x < keySize; x++)
            {
                machineKeyString += (char)random.Next(33, 126);
            }

            return machineKeyString.ConvertToSecureString();
        }
Esempio n. 3
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");
			}
		}
Esempio n. 4
0
		private void randomTest(
			SecureRandom srng)
		{
			int DAT_LEN = srng.Next(1024);
			byte[] nonce = new byte[NONCE_LEN];
			byte[] authen = new byte[AUTHEN_LEN];
			byte[] datIn = new byte[DAT_LEN];
			byte[] key = new byte[16];
			srng.NextBytes(nonce);
			srng.NextBytes(authen);
			srng.NextBytes(datIn);
			srng.NextBytes(key);

			AesFastEngine engine = new AesFastEngine();
			KeyParameter sessKey = new KeyParameter(key);
			EaxBlockCipher eaxCipher = new EaxBlockCipher(engine);

			AeadParameters parameters = new AeadParameters(sessKey, MAC_LEN * 8, nonce, authen);
			eaxCipher.Init(true, parameters);

			byte[] intrDat = new byte[eaxCipher.GetOutputSize(datIn.Length)];
			int outOff = eaxCipher.ProcessBytes(datIn, 0, DAT_LEN, intrDat, 0);
			outOff += eaxCipher.DoFinal(intrDat, outOff);

			eaxCipher.Init(false, parameters);
			byte[] datOut = new byte[eaxCipher.GetOutputSize(outOff)];
			int resultLen = eaxCipher.ProcessBytes(intrDat, 0, outOff, datOut, 0);
			eaxCipher.DoFinal(datOut, resultLen);

			if (!AreEqual(datIn, datOut))
			{
				Fail("EAX roundtrip failed to match");
			}
		}
		/**
		 * Generates a permuted ArrayList from the original one. The original List
		 * is not modified
		 *
		 * @param arr
		 *            the ArrayList to be permuted
		 * @param rand
		 *            the source of Randomness for permutation
		 * @return a new IList with the permuted elements.
		 */
		private static IList permuteList(
			IList           arr,
			SecureRandom    rand)
		{
            // TODO Create a utility method for generating permutation of first 'n' integers

            IList retval = Platform.CreateArrayList(arr.Count);

			foreach (object element in arr)
			{
				int index = rand.Next(retval.Count + 1);
				retval.Insert(index, element);
			}

			return retval;
		}
 private string GetUglyRandomString()
 {
     StringBuilder sb = new StringBuilder(128);
     for (int i = 0; i < 64; i++) {
         SecureRandom sr = new SecureRandom();
         int idx = sr.Next(0, 61);
         sb.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".Substring(idx, 1));
     }
     return sb.ToString();
 }
Esempio n. 7
0
 public static int RandomInt(int min = 0, int max = int.MaxValue)
 {
     var randr = new SecureRandom();
     return randr.Next(min, max);
 }
Esempio n. 8
0
		public override void PerformTest()
		{
			DerApplicationSpecific app = (DerApplicationSpecific)
				Asn1Object.FromByteArray(longTagged);

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

			Asn1InputStream 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 + ")");
				}
			}
		}
		/**
		 * Generates a permuted ArrayList from the original one. The original List
		 * is not modified
		 *
		 * @param arr
		 *            the ArrayList to be permuted
		 * @param rand
		 *            the source of Randomness for permutation
		 * @return a new ArrayList with the permuted elements.
		 */
		private static ArrayList permuteList(
			ArrayList arr,
			SecureRandom rand)
		{
			ArrayList retval = new ArrayList(arr.Count);

			foreach (object element in arr)
			{
				int index = rand.Next(retval.Count + 1);
				retval.Insert(index, element);
			}

			return retval;
		}
Esempio n. 10
0
        /// <summary>
        /// Randomizes the password set in this certificate.
        /// </summary>
        public void RandomizePassword() {
            const string characters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
            String password = "";

            SecureRandom random = new SecureRandom(new CryptoApiRandomGenerator());

            while (password.Length < 15) {
                password += characters[random.Next(characters.Length)];
            }

            this.Password = password;
        }
Esempio n. 11
0
		private void rawModeTest(string sigName, DerObjectIdentifier digestOID,
			AsymmetricKeyParameter privKey, AsymmetricKeyParameter pubKey, SecureRandom random)
		{
			byte[] sampleMessage = new byte[1000 + random.Next() % 100];
			random.NextBytes(sampleMessage);

			ISigner normalSig = SignerUtilities.GetSigner(sigName);
			normalSig.Init(true, privKey);
			normalSig.BlockUpdate(sampleMessage, 0, sampleMessage.Length);
			byte[] normalResult = normalSig.GenerateSignature();
			
			byte[] hash = DigestUtilities.CalculateDigest(digestOID.Id, sampleMessage);
			byte[] digInfo = derEncode(digestOID, hash);
			
			ISigner rawSig = SignerUtilities.GetSigner("RSA");
			rawSig.Init(true, privKey);
			rawSig.BlockUpdate(digInfo, 0, digInfo.Length);
			byte[] rawResult = rawSig.GenerateSignature();
			
			if (!Arrays.AreEqual(normalResult, rawResult))
			{
				Fail("raw mode signature differs from normal one");
			}

			rawSig.Init(false, pubKey);
			rawSig.BlockUpdate(digInfo, 0, digInfo.Length);

			if (!rawSig.VerifySignature(rawResult))
			{
				Fail("raw mode signature verification failed");
			}
		}
Esempio n. 12
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 keypair
			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");
			}
		}
Esempio n. 13
0
		private void rawModeTest(string sigName, DerObjectIdentifier digestOID,
			AsymmetricKeyParameter privKey, AsymmetricKeyParameter pubKey, SecureRandom random)
		{
			byte[] sampleMessage = new byte[1000 + random.Next() % 100];
			random.NextBytes(sampleMessage);

			ISigner normalSig = SignerUtilities.GetSigner(sigName);

			// FIXME
//			PSSParameterSpec spec = (PSSParameterSpec)normalSig.getParameters().getParameterSpec(PSSParameterSpec.class);

			// Make sure we generate the same 'random' salt for both normal and raw signers
			// FIXME
//			int saltLen = spec.getSaltLength();
//			byte[] fixedRandomBytes = new byte[saltLen];
			byte[] fixedRandomBytes = new byte[128];
			random.NextBytes(fixedRandomBytes);

			normalSig.Init(true, new ParametersWithRandom(privKey, FixedSecureRandom.From(fixedRandomBytes)));
			normalSig.BlockUpdate(sampleMessage, 0, sampleMessage.Length);
			byte[] normalResult = normalSig.GenerateSignature();

			byte[] hash = DigestUtilities.CalculateDigest(digestOID.Id, sampleMessage);
		
			ISigner rawSig = SignerUtilities.GetSigner("RAWRSASSA-PSS");

			// Need to init the params explicitly to avoid having a 'raw' variety of every PSS algorithm
			// FIXME
//			rawSig.setParameter(spec);

			rawSig.Init(true, new ParametersWithRandom(privKey, FixedSecureRandom.From(fixedRandomBytes)));
			rawSig.BlockUpdate(hash, 0, hash.Length);
			byte[] rawResult = rawSig.GenerateSignature();

			if (!Arrays.AreEqual(normalResult, rawResult))
			{
				Fail("raw mode signature differs from normal one");
			}

			rawSig.Init(false, pubKey);
			rawSig.BlockUpdate(hash, 0, hash.Length);

			if (!rawSig.VerifySignature(rawResult))
			{
				Fail("raw mode signature verification failed");
			}
		}
Esempio n. 14
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");
            }
        }