Exemple #1
0
        /// <summary>
        /// Тест Миллера — Рабина на простоту
        /// </summary>
        /// <param name="n">Тестируемое число</param>
        /// <param name="testCount">Колличество итераций проверки</param>
        /// <returns></returns>
        public static bool IsPrime(this BigInteger n, uint testCount = 20)
        {
            if (testCount < 10)
            {
                throw new ArgumentException("test count must be greater 10");
            }

            if (n.Sign != 1)
            {
                throw new ArgumentException("n must be positive");
            }

            if (n == 2)
            {
                return(true);
            }
            if (n.IsEven)
            {
                return(false);
            }


            ulong      s = 0;
            BigInteger t = n - 1;

            while (t.IsEven)
            {
                s++;

                t = t >> 1;
            }

            for (uint i = 0; i < testCount; i++)
            {
                BigInteger a = NumMethodsClass.GenerateBigInteger(2, n - 2);
                BigInteger x = BigInteger.ModPow(a, t, n);
                if ((x == BigInteger.One) || (x == (n - 1)))
                {
                    continue;
                }
                for (ulong j = 0; j < (s - 1); j++)
                {
                    x = BigInteger.ModPow(x, 2, n);
                    if (x == BigInteger.One)
                    {
                        return(false);
                    }
                    if (x == (n - 1))
                    {
                        break;
                    }
                }
                if (x != (n - 1))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemple #2
0
        private void RegenerateSizeParameters()
        {
            int keySize = NumMethodsClass.GetModuleSize(BigInteger.Parse(GeneralParameter));

            _readingSize = keySize - 1;
            _packingSize = keySize;
        }
Exemple #3
0
        public void GenerateKey()
        {
            try
            {
                BigInteger p                  = NumMethodsClass.GeneratePrime(95);
                BigInteger q                  = NumMethodsClass.GeneratePrime(98);
                BigInteger modulus            = p * q;
                BigInteger phi                = (p - 1) * (q - 1);
                BigInteger pubExp             = NumMethodsClass.GetPublicExponent(p.ToString(), q.ToString());;
                BigInteger privateExponentInt = pubExp.Inverse(phi);
                if (privateExponentInt == 0)
                {
                    throw new ApplicationException();
                }

                _modulus        = modulus.ToString();
                _phi            = phi.ToString();
                _openExponent   = pubExp.ToString();
                _secretExponent = privateExponentInt.ToString();
                RegenerateSizeParameters();
            }
            catch (Exception)
            {
                throw new ApplicationException("Error via generate key");
            }
        }
Exemple #4
0
        private void RegenerateSizeParameters()
        {
            string modulus = GeneralParameter.Split(" ")[0];
            int    keySize = NumMethodsClass.GetModuleSize(BigInteger.Parse(modulus));

            _readingSize = keySize - 1;
            _packingSize = keySize;
        }
Exemple #5
0
        public byte[] Sign(IKey Key, byte[] hash)
        {
            byte[] hashBytes = hash;
            if (Key.IsKeyValid(isSigning: true))
            {
                List <byte> result = new List <byte>();

                string[] generalList = Key.GeneralParameter.Split(" ");

                BigInteger p = BigInteger.Parse(generalList[0]);
                BigInteger q = BigInteger.Parse(generalList[1]);
                BigInteger g = BigInteger.Parse(generalList[2]);
                BigInteger x = BigInteger.Parse(Key.SecretParameter);

                BigInteger k = BigInteger.Zero;
                BigInteger r = BigInteger.Zero;

                do
                {
                    k = NumMethodsClass.GenerateBigInteger(1, q - 1);
                    BigInteger temp = BigInteger.ModPow(g, k, p);
                    BigInteger.DivRem(temp, q, out r);
                } while (r == 0);

                int countOfBytes = hashBytes.Length; // calculate count of bytes in block

                byte[] block = new byte[countOfBytes + 1];

                Buffer.BlockCopy(hashBytes, 0, block, 0, countOfBytes);

                BigInteger s = BigInteger.Zero;

                BigInteger.DivRem(k.Inverse(q) * (new BigInteger(block) + x * r), q, out s);

                if (s == BigInteger.Zero)
                {
                    throw new ApplicationException("Generate keys again. Invalid keys");
                }

                byte[] tempResult = s.ToByteArray();

                byte[] packingUnit = new byte[hashBytes.Length];

                Buffer.BlockCopy(tempResult, 0, packingUnit, 0, Math.Min(tempResult.Length, hashBytes.Length)); //copy to packing block from result of ciphering

                result.AddRange(packingUnit);

                result.AddRange(r.ToByteArray());

                return(result.ToArray());
            }
            else
            {
                throw new ApplicationException("Key is not valid");
            }
        }
        public MainWindow()
        {
            Thread thread = new Thread(() =>
            {
                NumMethodsClass.LoadPyScript();
            });

            thread.Start();
            InitializeComponent();
            DataContext = new SignToolMainVM();
        }
        private ElgamalPrivateKey GetElgamalPrivateKey(ElgamalPublicParams param)
        {
            ElgamalPublicParams parameters = param;
            ElgamalPrivateKey   pk;
            BigInteger          x;
            BigInteger          y;

            x = NumMethodsClass.GenerateBigInteger(2, parameters.Modulus - 1);

            y = CalculateKeysByPowm(parameters.Generator, x, parameters.Modulus);

            pk.X = x;
            pk.Y = y;
            return(pk);
        }
Exemple #8
0
        public static BigInteger Inverse(this BigInteger a, BigInteger module)
        {
            var result = NumMethodsClass.GCDex(a, module);

            if (result.d != BigInteger.One)
            {
                return(0);
            }

            BigInteger.DivRem(result.x, module, out result.x);
            if (result.x.Sign == -1)
            {
                result.x += module;
                BigInteger.DivRem(result.x, module, out result.x);
            }
            return(result.x);
        }
Exemple #9
0
        public static DHPublicParams Generate(int decimalNubmerCount)
        {
            BigInteger min = BigInteger.Pow(10, decimalNubmerCount);
            BigInteger max = BigInteger.Pow(10, decimalNubmerCount + 1);

            BigInteger p;
            BigInteger q;

            while (true)
            {
                q = NumMethodsClass.GenerateBigInteger(min, max);
                if (q.IsPrime())
                {
                    p = (q << 1) + BigInteger.One;

                    if (p.IsPrime())
                    {
                        break;
                    }
                }
            }


            BigInteger pMinusOne = p - 1;
            BigInteger g;

            do
            {
                g = NumMethodsClass.GenerateBigInteger(2, pMinusOne);
            } while (BigInteger.ModPow(g, 2, p) == BigInteger.One ||
                     BigInteger.ModPow(g, q, p) == BigInteger.One);

            DHPublicParams dHPublic;

            dHPublic.Modulus   = p;
            dHPublic.Generator = g;
            return(dHPublic);
        }
Exemple #10
0
        public void GenerateKey()
        {
            BigInteger q = NumMethodsClass.GeneratePrimeByPython(160);
            BigInteger p;
            BigInteger b;

            do
            {
                b = NumMethodsClass.GenerateBigInteger((1024 - 160) / 8);
                p = b * q + 1;
            } while (!p.IsPrime());

            BigInteger g = BigInteger.Zero;

            for (BigInteger i = 2; i < p - 1; i++)
            {
                g = BigInteger.ModPow(i, b, p);
                if (g > 1)
                {
                    break;
                }
            }

            if (g == BigInteger.Zero)
            {
                throw new ApplicationException("Try generate again, error via generating G");
            }

            BigInteger x = NumMethodsClass.GenerateBigInteger(2, q - 1);
            BigInteger y = BigInteger.ModPow(g, x, p);

            GeneralParameter = $"{p.ToString()} {q.ToString()} {g.ToString()}";
            OpenParameter    = y.ToString();
            SecretParameter  = x.ToString();
            RegenerateSizeParameters();
        }
Exemple #11
0
        public byte[] Sign(IKey Key, byte[] hash)
        {
            byte[]      hashBytes = hash;
            List <byte> result    = new List <byte>(hashBytes.Length);

            if (!Key.IsKeyValid(isSigning: true))
            {
                throw new ApplicationException("Key is not valid");
            }

            try
            {
                int readSize  = Key.ReadingSize;
                int writeSize = Key.PackingSize;

                BigInteger k;
                string[]   generalParameters = Key.GeneralParameter.Split(" ");
                BigInteger modulus           = BigInteger.Parse(generalParameters[0]);
                BigInteger generator         = BigInteger.Parse(generalParameters[1]);
                BigInteger secret            = BigInteger.Parse(Key.SecretParameter);
                do
                {
                    k = NumMethodsClass.GenerateBigInteger(2, modulus - 3);
                } while (BigInteger.GreatestCommonDivisor(k, modulus - 1) != 1);

                BigInteger r = BigInteger.ModPow(generator, k, modulus);

                byte[] packedBlock = new byte[writeSize];

                byte[] rBlock = r.ToByteArray(false);
                Buffer.BlockCopy(rBlock, 0, packedBlock, 0, rBlock.Length);
                result.AddRange(packedBlock);

                for (int currentByte = 0; currentByte < hashBytes.Length; currentByte += readSize)
                {
                    int    byteCopyCount = Math.Min(readSize, hashBytes.Length - currentByte);
                    byte[] currentBlock  = new byte[byteCopyCount + 1]; // Добавлен 0х00 чтобы число было положительным

                    Buffer.BlockCopy(hashBytes, currentByte, currentBlock, 0, byteCopyCount);
                    BigInteger h = new BigInteger(currentBlock);

                    BigInteger temp;
                    BigInteger.DivRem(secret * r, modulus - 1, out temp);


                    BigInteger u;
                    BigInteger.DivRem(h - temp + (modulus - 1), modulus - 1, out u);

                    BigInteger s;
                    BigInteger.DivRem(k.Inverse(modulus - 1) * u, modulus - 1, out s);

                    byte[] cipherBlock = s.ToByteArray(false);
                    packedBlock = new byte[writeSize];
                    Buffer.BlockCopy(cipherBlock, 0, packedBlock, 0, cipherBlock.Length);
                    result.AddRange(packedBlock);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(result.ToArray());
        }