Ejemplo n.º 1
0
        private static void ZKPCracker()
        {
            System.Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            System.Console.Write("\nn: ");
            Integer n = Tools.ToInteger(Console.ReadLine());
            Integer p;

            while (true)
            {
                var t = MathI.RandomI();
                var y = t.ModPow(2, n);
                System.Console.WriteLine($"y: {y.ToHexString()}");
                System.Console.Write("z: ");
                var z = Tools.ToInteger(Console.ReadLine());
                if (y != z || y != -z)
                {
                    p = NumberTheory.GCD(t + z, n);
                    if (p != 1)
                    {
                        break;
                    }
                }
                System.Console.WriteLine("___________________");
            }

            System.Console.WriteLine("\n\nEnd of attack");
            var q = n / p;

            System.Console.WriteLine($"p: {p.ToHexString()}");
            System.Console.WriteLine($"q: {q.ToHexString()}");
            System.Console.WriteLine($"Test n: {(p * q).ToHexString()}");
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Generic Z_n FPE encryption, FE1 scheme
        /// </summary>
        /// <param name="modulus">Use to determine the range of the numbers. Example, if the
        /// numbers range from 0 to 999, use "1000" here.</param>
        /// <param name="plaintext">The number to encrypt.</param>
        /// <param name="key">Secret key</param>
        /// <param name="tweak">Non-secret parameter, think of it as an IV</param>
        /// <returns>The encrypted number.</returns>
        public static BigInteger Encrypt(BigInteger modulus, BigInteger plaintext,
                                         byte[] key,
                                         byte[] tweak)
        {
            FPE_Encryptor F = new FPE_Encryptor(key, modulus, tweak);

            BigInteger a, b;

            NumberTheory.factor(modulus, out a, out b);

            int r = rounds(a, b);

            BigInteger X = plaintext;

            for (int i = 0; i != r; ++i)
            {
                BigInteger L = X / b;
                BigInteger R = X.mod(b);

                BigInteger W = (L + F.F(i, R)).mod(a);
                X = a * R + W;
            }

            return(X);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Finds greatest prime factor.
        /// </summary>
        public static long Q003(long n)
        {
            // n > 1;
            List <long> factors = new List <long>();

            factors.Add(n);

            long sqrt = (long)Math.Floor(Math.Sqrt(n));

            for (long i = 2; i <= sqrt; i++)
            {
                if (n % i == 0)
                {
                    factors.Add(i);
                    factors.Add(n / i);
                }
            }

            factors.Sort();
            for (int i = factors.Count - 1; i >= 0; i--)
            {
                if (NumberTheory.IsPrime(factors[i]))
                {
                    return(factors[i]);
                }
            }

            return(-1);
        }
Ejemplo n.º 4
0
        public void FindCGDForShortArraySuccess()
        {
            int[] array = { 5 };
            int   cgd   = 5;

            Assert.AreEqual(cgd, NumberTheory.FindCGDForArrayElements(array));
        }
Ejemplo n.º 5
0
        public KeyPair ComposeKey(BigInteger e, PrimePair primes)
        {
            var n = primes.P * primes.Q;

            // Checks to avoid exceptions
            if (primes.P == 0 || primes.Q == 0 || e == 0)
            {
                throw new Exception("Invalid p, q, e provided for CRT Key");
                //return new KeyPair
                //{
                //    PrivKey = new CrtPrivateKey {P = primes.P, Q = primes.Q},
                //    PubKey = new PublicKey {E = e, N = n}
                //};
            }

            var d = e.ModularInverse(NumberTheory.LCM(primes.P - 1, primes.Q - 1));

            return(new KeyPair
            {
                PrivKey = new CrtPrivateKey
                {
                    DMP1 = d % (primes.P - 1),
                    DMQ1 = d % (primes.Q - 1),
                    IQMP = primes.Q.ModularInverse(primes.P),
                    P = primes.P,
                    Q = primes.Q
                },
                PubKey = new PublicKey
                {
                    E = e,
                    N = n
                }
            });
        }
Ejemplo n.º 6
0
    public Fraction(long numerator, long denominator)
    {
        long GreatestCommonDivisor = NumberTheory.GCD(numerator, denominator);

        m_numerator   = numerator / GreatestCommonDivisor;
        m_denominator = denominator / GreatestCommonDivisor;
    }
Ejemplo n.º 7
0
        /// <summary>
        /// Generic Z_n FPE decryption, FD1 scheme
        /// </summary>
        /// <param name="modulus">Use to determine the range of the numbers. Example, if the
        /// numbers range from 0 to 999, use "1000" here.</param>
        /// <param name="ciphertext">The number to decrypt.</param>
        /// <param name="key">Secret key</param>
        /// <param name="tweak">Non-secret parameter, think of it as an IV - use the same one used to encrypt</param>
        /// <returns>The decrypted number</returns>
        public static BigInteger Decrypt(BigInteger modulus, BigInteger ciphertext,
                                         byte[] key,
                                         byte[] tweak)
        {
            FPE_Encryptor F = new FPE_Encryptor(key, modulus, tweak);

            BigInteger a, b;

            NumberTheory.factor(modulus, out a, out b);

            int r = rounds(a, b);

            BigInteger X = ciphertext;

            for (int i = 0; i != r; ++i)
            {
                BigInteger W = X.mod(a);
                BigInteger R = X / a;

                BigInteger bigInteger = (W - F.F(r - i - 1, R));

                BigInteger L = bigInteger.mod(a);
                X = b * L + R;
            }

            return(X);
        }
Ejemplo n.º 8
0
        private void f3_buttonSetKeys_Click(object sender, EventArgs e)
        {
            f3_textP.Text = new string(f3_textP.Text.Where(t => char.IsDigit(t)).ToArray());
            f3_textQ.Text = new string(f3_textQ.Text.Where(t => char.IsDigit(t)).ToArray());
            f3_textG.Text = new string(f3_textG.Text.Where(t => char.IsDigit(t)).ToArray());

            BigInteger p = 0, q = 0, g = 0;

            if (f3_textP.TextLength > 0 && f3_textQ.TextLength > 0 && f3_textG.TextLength > 0 &&
                RabinMiller.IsPrime(p = BigInteger.Parse(f3_textP.Text), 10) &&
                RabinMiller.IsPrime(q = BigInteger.Parse(f3_textQ.Text), 10) &&
                ((g = BigInteger.Parse(f3_textG.Text)) >= 2) && g < p - 1 && NumberTheory.BinaryModPow(g, q, p) != 1)
            {
                DiffieHellman.Params.P = p;
                DiffieHellman.Params.Q = q;
                DiffieHellman.Params.G = g;

                f3_buttonSetKeys.Enabled       = false;
                f3_buttonClearKeys.Enabled     = true;
                f3_buttonNextPrime.Enabled     = false;
                f3_buttonNextGenerator.Enabled = false;

                f3_textQ.ReadOnly = true;
                f3_textG.ReadOnly = true;

                f3_button_SetSecretA.Enabled       = true;
                f3_button_GetRandomSecretA.Enabled = true;
                f3_textSecretA.ReadOnly            = false;
                f3_button_SetSecretB.Enabled       = true;
                f3_button_GetRandomSecretB.Enabled = true;
                f3_textSecretB.ReadOnly            = false;
            }
        }
Ejemplo n.º 9
0
        // Q010: 142913828922;
        public static long Q010()
        {
            int        n      = 2000000;
            List <int> primes = NumberTheory.GetPrimesBelow(n);

            // 148933 primes;
            return(primes.Select(i => (long)i).Sum());
        }
Ejemplo n.º 10
0
        public static BigInteger AssociateValueFunction(int qExactLength, EccKeyPair publicKey)
        {
            int f = (qExactLength + 1) / 2;

            BigInteger pow2 = NumberTheory.Pow2(f);

            return(pow2 + (publicKey.PublicQ.X % pow2));
        }
Ejemplo n.º 11
0
        public KdfResult DeriveKey(BitString kI, BitString fixedData, int len, BitString iv = null, int breakLocation = 0)
        {
            // 1
            var n = len.CeilingDivide(Mac.OutputLength);

            // 2
            if (n > NumberTheory.Pow2(_counterLength) - 1)
            {
                return(new KdfResult("Counter length too long for operation"));
            }

            // 3
            var result = new BitString(0);

            // 4
            if (_counterLocation == CounterLocations.MiddleFixedData)
            {
                if (breakLocation < 1 || breakLocation > fixedData.BitLength - 1)
                {
                    return(new KdfResult("Invalid break location"));
                }
            }

            for (var i = 1; i <= n; i++)
            {
                var counterBits = BitString.To32BitString(i).GetLeastSignificantBits(_counterLength);
                var data        = new BitString(0);

                switch (_counterLocation)
                {
                case CounterLocations.BeforeFixedData:
                    data = data.ConcatenateBits(counterBits).ConcatenateBits(fixedData);
                    break;

                case CounterLocations.AfterFixedData:
                    data = data.ConcatenateBits(fixedData).ConcatenateBits(counterBits);
                    break;

                case CounterLocations.MiddleFixedData:
                    var firstPart  = fixedData.GetMostSignificantBits(breakLocation);
                    var secondPart = fixedData.MSBSubstring(breakLocation, fixedData.BitLength - breakLocation);
                    data = data.ConcatenateBits(firstPart).ConcatenateBits(counterBits).ConcatenateBits(secondPart);
                    break;

                default:
                    return(new KdfResult("Invalid Counter location"));
                }

                var kTemp = PseudoRandomFunction(kI, data);

                result = result.ConcatenateBits(kTemp);
            }

            // 5
            var kOut = result.GetMostSignificantBits(len);

            return(new KdfResult(kOut));
        }
Ejemplo n.º 12
0
        public EdSignatureResult Sign(EdDomainParameters domainParameters, EdKeyPair keyPair, BitString message, BitString context, bool preHash = false)
        {
            Sha = domainParameters.Hash;

            // If preHash version, then the message becomes the hash of the message
            if (preHash)
            {
                message = Sha.HashMessage(message, 512).Digest;
            }

            // 1. Hash the private key
            var hashResult = HashPrivate(domainParameters, keyPair.PrivateD);

            // 2. Compute r
            // Determine dom. Empty if ed25519. Different for preHash function
            BitString dom;
            if (preHash)
            {
                dom = domainParameters.CurveE.CurveName == Curve.Ed448 ? Dom4(1, context) : Dom2(1, context);
            }
            else
            {
                dom = domainParameters.CurveE.CurveName == Curve.Ed448 ? Dom4(0, context) : new BitString("");
            }

            // Hash (dom4 || Prefix || message)
            var rBits = Sha.HashMessage(BitString.ConcatenateBits(dom, BitString.ConcatenateBits(hashResult.HDigest2, message)), 912).Digest;

            // Convert rBits to little endian and mod order n
            var r = BitString.ReverseByteOrder(rBits).ToPositiveBigInteger() % domainParameters.CurveE.OrderN;

            // 3. Compute [r]G. R is the encoding of [r]G
            var rG = domainParameters.CurveE.Multiply(domainParameters.CurveE.BasePointG, r);

            // Encode the point rG into a b-bit bitstring
            var R = domainParameters.CurveE.Encode(rG);

            // 4. Define S
            // Hash (dom4 || R || Q || M). Need to use dom4 if ed448
            var hashData = BitString.ConcatenateBits(keyPair.PublicQ, message);
            hashData = BitString.ConcatenateBits(dom, BitString.ConcatenateBits(R, hashData));
            var hash = Sha.HashMessage(hashData, 912).Digest;

            // Convert hash to int from little endian and mod order n
            var hashInt = BitString.ReverseByteOrder(hash).ToPositiveBigInteger() % domainParameters.CurveE.OrderN;

            // Determine s as done in key generation
            var s = NumberTheory.Pow2(domainParameters.CurveE.VariableN) + hashResult.Buffer.ToPositiveBigInteger();

            // Calculate S as an BigInteger
            var Sint = (r + (hashInt * s)).PosMod(domainParameters.CurveE.OrderN);

            // Encode S in little endian
            var S = BitString.ReverseByteOrder(new BitString(Sint, domainParameters.CurveE.VariableB));

            // 5. Form the signature by concatenating R and S
            return new EdSignatureResult(new EdSignature(R, S));
        }
Ejemplo n.º 13
0
        public static bool IsValidExponent(BigInteger e)
        {
            if (e <= NumberTheory.Pow2(16) || e >= NumberTheory.Pow2(256) || e.IsEven)
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 14
0
        public void GCDTest(long a, long b)
        {
            //action
            long gcd = NumberTheory.GCD(a, b);

            //assert
            (a % gcd).Should().Be(0L);
            (b % gcd).Should().Be(0L);
        }
Ejemplo n.º 15
0
        public int Encrypt(int p, int q, int M, int e)
        {
            // Get n
            long         n    = p * q;
            NumberTheory calc = new NumberTheory();
            // Get C = M^e mod n
            int C = (int)calc.FastPower(M, e, n);

            return(C);
        }
Ejemplo n.º 16
0
 static void TestLCM(Integer expected, Integer a, Integer b)
 {
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(a, b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(b, a));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-a, b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-b, a));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(a, -b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(b, -a));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-a, -b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-b, -a));
 }
Ejemplo n.º 17
0
 static void TestGCD(Integer expected, Integer a, Integer b)
 {
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(a, b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(b, a));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-a, b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-b, a));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(a, -b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(b, -a));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-a, -b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-b, -a));
 }
Ejemplo n.º 18
0
        public int Decrypt(int p, int q, int C, int e)
        {
            long n = p * q;
            // Get phi(n)
            // Call Euclidean Extended to get d
            NumberTheory calc = new NumberTheory();
            long         d    = calc.GetMultiplicativeInverse(e, calc.Phi(p, q));
            // Get M = C^d mod d
            int M = (int)calc.FastPower(C, d, n);

            return(M);
        }
Ejemplo n.º 19
0
 static void TestGCD(int expected, int a, int b)
 {
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(a, b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(b, a));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-a, b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-b, a));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(a, -b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(b, -a));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-a, -b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-b, -a));
     TestGCD(expected, (long)a, (long)b);
 }
Ejemplo n.º 20
0
 static void TestGCD(long expected, long a, long b)
 {
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(a, b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(b, a));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-a, b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-b, a));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(a, -b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(b, -a));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-a, -b));
     Assert.AreEqual(expected, NumberTheory.GreatestCommonFactor(-b, -a));
     TestGCD(expected, (Integer)a, (Integer)b);
 }
Ejemplo n.º 21
0
 static void TestLCM(Integer expected, long a, long b)
 {
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(a, b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(b, a));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-a, b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-b, a));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(a, -b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(b, -a));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-a, -b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-b, -a));
     TestLCM(expected, (Integer)a, (Integer)b);
 }
Ejemplo n.º 22
0
 static void TestLCM(long expected, int a, int b)
 {
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(a, b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(b, a));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-a, b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-b, a));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(a, -b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(b, -a));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-a, -b));
     Assert.AreEqual(expected, NumberTheory.LeastCommonMultiple(-b, -a));
     TestLCM(expected, (long)a, (long)b);
 }
Ejemplo n.º 23
0
        public void TestExtendedEuclid()
        {
            var result = NumberTheory.ExtendedEuclid(6, 4);

            Console.WriteLine("{0}, {1}, {2}", result.Item1, result.Item2, result.Item3);

            result = NumberTheory.ExtendedEuclid(120, 23);
            Console.WriteLine("{0}, {1}, {2}", result.Item1, result.Item2, result.Item3);
            CollectionAssert.AreEqual(new int[] { result.Item1, result.Item2, result.Item3 }, new int[] { 1, -9, 47 });

            result = NumberTheory.ExtendedEuclid(31415, 14142);
            Console.WriteLine("{0}, {1}, {2}", result.Item1, result.Item2, result.Item3);
        }
Ejemplo n.º 24
0
        public void TestGetPrimesBelow()
        {
            int        n      = 10;
            List <int> primes = NumberTheory.GetPrimesBelow(n);

            Assert.That(primes.Count, Is.EqualTo(4));
            Assert.That(primes.Sum(), Is.EqualTo(17));

            n      = 2000000;
            primes = NumberTheory.GetPrimesBelow(n);
            Assert.That(primes.Count, Is.EqualTo(148933));
            Assert.That(primes.Select(i => (long)i).Sum(), Is.EqualTo(17));
        }
Ejemplo n.º 25
0
 private void f4_textStepB3_TextChanged(object sender, EventArgs e)
 {
     f4_textStepB4.Text = "";
     if (f4_textStepB3.TextLength > 0)
     {
         BigInteger x3 = BigInteger.Parse(f4_textStepB3.Text);
         BigInteger p  = BigInteger.Parse(f4_textP.Text);
         BigInteger Db = BigInteger.Parse(f4_textDb.Text);
         //Шаг 4 шифрования
         BigInteger x4 = NumberTheory.BinaryModPow(x3, Db, p);
         f4_textStepB4.Text = Convert.ToString(x4);
     }
 }
Ejemplo n.º 26
0
 private void f5_RecievedCiphertext_TextChanged(object sender, EventArgs e)
 {
     if (f5_RecievedCiphertext.TextLength > 0)
     {
         //Расшифрование
         BigInteger r         = BigInteger.Parse(f5_textOpenA_inWindowB.Text); // Открытый ключ Алисы
         BigInteger CB        = BigInteger.Parse(f5_textSecretB.Text);         //Секретный ключ Боба
         BigInteger p         = BigInteger.Parse(f5_textP.Text);               //параметр системы
         BigInteger cipher    = BigInteger.Parse(f5_RecievedCiphertext.Text);  //шифртекст (e)
         BigInteger m         = (cipher * NumberTheory.BinaryModPow(r, ((p - 1) - CB), p)) % p;
         int        letterNum = (int)m;
         f5_textBox_MessageBob.Text += MyAlphabets.AllTypesTogether[letterNum];
     }
 }
Ejemplo n.º 27
0
        private void f4_button_GetRandomCb_Click(object sender, EventArgs e)
        {
            BigInteger            P = BigInteger.Parse(f4_textP.Text);
            RandomNumberGenerator rng = RandomNumberGenerator.Create();
            BigInteger            Db, Cb = BigIntegerRandomUtils.RandomInRange(rng, 2, P - 1);

            while (!(NumberTheory.GCD(Cb, P - 1, out BigInteger x, out BigInteger y) == 1))
            {
                Cb = BigIntegerRandomUtils.RandomInRange(rng, 2, P - 1);
            }
            ;

            f4_textCb.Text = Convert.ToString(Cb);
        }
Ejemplo n.º 28
0
 private void f4_textStepB1_TextChanged(object sender, EventArgs e)
 {
     f4_textStepA2.Text = "";
     f4_textStepB2.Text = "";
     if (f4_textStepB1.TextLength > 0)
     {
         BigInteger x1 = BigInteger.Parse(f4_textStepB1.Text);
         BigInteger p  = BigInteger.Parse(f4_textP.Text);
         BigInteger Cb = BigInteger.Parse(f4_textCb.Text);
         //Шаг 2 шифрования
         BigInteger x2 = NumberTheory.BinaryModPow(x1, Cb, p);
         f4_textStepA2.Text = Convert.ToString(x2);
         f4_textStepB2.Text = Convert.ToString(x2);
     }
 }
Ejemplo n.º 29
0
        private void f9_button_GetRandomSecret_Click(object sender, EventArgs e)
        {
            RandomNumberGenerator rng       = RandomNumberGenerator.Create();
            BigInteger            N         = BigInteger.Parse(f9_textN.Text);
            BigInteger            P         = BigInteger.Parse(f9_textP.Text);
            BigInteger            Q         = BigInteger.Parse(f9_textQ.Text);
            BigInteger            fi        = (P - 1) * (Q - 1); // Функция Эйлера от N
            BigInteger            SecretKey = BigIntegerRandomUtils.RandomInRange(rng, 2, N - 1);

            while (NumberTheory.GCD(SecretKey, fi, out BigInteger x, out BigInteger y) != 1)
            {
                SecretKey = BigIntegerRandomUtils.RandomInRange(rng, 2, N - 1);
            }
            f9_textSecretKey.Text = Convert.ToString(SecretKey);
        }
Ejemplo n.º 30
0
 private void f4_textStepA2_TextChanged(object sender, EventArgs e)
 {
     f4_textStepA3.Text = "";
     f4_textStepB3.Text = "";
     if (f4_textStepA2.TextLength > 0)
     {
         BigInteger x2 = BigInteger.Parse(f4_textStepA2.Text);
         BigInteger p  = BigInteger.Parse(f4_textP.Text);
         BigInteger Da = BigInteger.Parse(f4_textDa.Text);
         //Шаг 3 шифрования
         BigInteger x3 = NumberTheory.BinaryModPow(x2, Da, p);
         f4_textStepA3.Text = Convert.ToString(x3);
         f4_textStepB3.Text = Convert.ToString(x3);
     }
 }