genRandomBits() public method

public genRandomBits ( int bits, Random rand ) : void
bits int
rand Random
return void
Ejemplo n.º 1
0
        internal void Setup()
        {
            _b = new BigInteger();
            _b.genRandomBits(256, new Random((int)DateTime.Now.Ticks));

            _B = (_k * _v) + (_g.modPow(_b, _N));
            while (_B % _N == 0)
            {
                _b.genRandomBits(256, new Random((int)DateTime.Now.Ticks));
                _B = (_k * _v) + (_g.modPow(_b, _N));
            }
            _Bstr = _B.ToString(16);
        }
Ejemplo n.º 2
0
        public void TestSecuredGenRandomBits()
        {
            { // Test < 32 bits
                var bi   = new BigInteger();
                var rng  = new RNGCryptoServiceProvider();
                var rand = new Random();

                bi.genRandomBits(rand.Next(33), rng);

                var bytes = bi.getBytes();
                Array.Reverse(bytes);
                var new_bytes = new byte[4];
                Array.Copy(bytes, new_bytes, bytes.Length);

                Assert.IsTrue(BitConverter.ToUInt32(new_bytes, 0) < (Math.Pow(2, 32) - 1));
            }

            { // Test upper boundary values
                var bi  = new BigInteger();
                var rng = new RNGCryptoServiceProvider();

                Exception exception = null;

                try
                {
                    bi.genRandomBits(2241, rng);
                }
                catch (Exception ex)
                {
                    exception = ex;
                }

                Assert.IsNotNull(exception);

                bi.genRandomBits(2240, rng);
                Assert.AreEqual(70, bi.dataLength);

                bi.genRandomBits(2239, rng);
                Assert.AreEqual(70, bi.dataLength);
            }

            { // Test lower boudary value
                var bi  = new BigInteger();
                var rng = new RNGCryptoServiceProvider();

                bi.genRandomBits(1, rng);
                Assert.IsTrue(bi.getBytes()[0] == 1 || bi.getBytes()[0] == 0);
            }
        }
Ejemplo n.º 3
0
        //формирование цифровой подписи.
        public string GenDs(byte[] h, BigInteger d)
        {
            var        a = new BigInteger(h);
            BigInteger e = a % _n;

            if (e == 0)
            {
                e = 1;
            }
            var        k = new BigInteger();
            BigInteger r;
            BigInteger s;

            do
            {
                do
                {
                    k.genRandomBits(_n.bitCount(), new Random());
                }while (k < 0 || k > _n);

                var c = EcPoint.Multiply(_g, k);
                r = c.X % _n;
                s = (r * d + k * e) % _n;
            }while (r == 0 || s == 0);

            string rvector = Padding(r.ToHexString(), _n.bitCount() / 4);
            string svector = Padding(s.ToHexString(), _n.bitCount() / 4);

            return(rvector + svector);
        }
Ejemplo n.º 4
0
        // private helper methods

        private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            }

            //using (var hmac = new System.Security.Cryptography.HMACSHA512())
            //{
            //	passwordSalt = hmac.Key;
            //	passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            //}

            BigInteger b = new BigInteger();

            b.genRandomBits(512, new Random());

            passwordSalt = b.getBytes();

            GostCrypto.Gost34102012Signer signer = new GostCrypto.Gost34102012Signer(new BigInteger(passwordSalt));
            passwordHash = Encoding.UTF8.GetBytes(signer.Sign(password));
        }
Ejemplo n.º 5
0
        protected override byte[] ProcessDataBlock(byte[] p_block)
        {
            BigInteger K;

            do
            {
                K = new BigInteger();
                K.genRandomBits(o_key_struct.P.bitCount() - 1, o_random);
            } while (K.gcd(o_key_struct.P - 1) != 1);

            BigInteger A = o_key_struct.G.modPow(K, o_key_struct.P);
            BigInteger B = (o_key_struct.Y.modPow(K, o_key_struct.P)
                            * new BigInteger(p_block)) % (o_key_struct.P);

            byte[] x_result = new byte[o_ciphertext_blocksize];

            byte[] x_a_bytes = A.getBytes();
            Array.Copy(x_a_bytes, 0, x_result, o_ciphertext_blocksize / 2
                       - x_a_bytes.Length, x_a_bytes.Length);
            byte[] x_b_bytes = B.getBytes();
            Array.Copy(x_b_bytes, 0, x_result, o_ciphertext_blocksize
                       - x_b_bytes.Length, x_b_bytes.Length);

            return(x_result);
        }
Ejemplo n.º 6
0
        public static byte[] CreateSignature(byte[] p_data, ElGamalKeyStruct p_key_struct)
        {
            BigInteger x_pminusone = p_key_struct.P - 1;
            // create K, which is the random number
            BigInteger K;

            do
            {
                K = new BigInteger();
                K.genRandomBits(p_key_struct.P.bitCount() - 1, new Random());
            } while (K.gcd(x_pminusone) != 1);

            BigInteger A = p_key_struct.G.modPow(K, p_key_struct.P);
            BigInteger B = mod(mod(K.modInverse(x_pminusone)
                                   * (new BigInteger(p_data)
                                      - (p_key_struct.X * (A))), (x_pminusone)), (x_pminusone));

            byte[] x_a_bytes = A.getBytes();
            byte[] x_b_bytes = B.getBytes();
            // define the result size
            int x_result_size = (((p_key_struct.P.bitCount() + 7) / 8) * 2);

            // create an array to contain the ciphertext
            byte[] x_result = new byte[x_result_size];
            // populate the arrays
            Array.Copy(x_a_bytes, 0, x_result, x_result_size / 2
                       - x_a_bytes.Length, x_a_bytes.Length);
            Array.Copy(x_b_bytes, 0, x_result, x_result_size
                       - x_b_bytes.Length, x_b_bytes.Length);

            // return the result array ..
            return(x_result);
        }
Ejemplo n.º 7
0
        //PROCESS_DATA_METHOD
        protected override byte[] ProcessDataBlock(byte[] plaintext_data_block)
        {
            // the random number, K
            BigInteger K;

            // create K, which is the random number
            do
            {
                K = new BigInteger();
                K.genRandomBits(current_key.P.bitCount() - 1, random_number);
            }while

            (K.gcd(current_key.P - 1) != 1);

            // compute the values  A = G exp K mod P
            // and B = ((Y exp K mod P) * plain_data_block) / P
            //Y is Alice's encrypted result (public key)
            BigInteger A = current_key.G.modPow(K, current_key.P);
            BigInteger B = (current_key.Y.modPow(K, current_key.P) * new BigInteger(plaintext_data_block)) % (current_key.P);

            // ciphertext
            byte[] cipher_result = new byte[ciphertext_blocksize];

            // copy the bytes from A and B into the result array which is cipher_result
            byte[] a_bytes = A.getBytes();
            Array.Copy(a_bytes, 0, cipher_result, ciphertext_blocksize / 2 - a_bytes.Length, a_bytes.Length); //96bit

            byte[] b_bytes = B.getBytes();
            Array.Copy(b_bytes, 0, cipher_result, ciphertext_blocksize - b_bytes.Length, b_bytes.Length); //96bit

            // return the result array after merging A and B
            return(cipher_result);
        }
Ejemplo n.º 8
0
            /// <summary>
            /// Generate a new SRP verifier. Password is the plaintext password.
            /// </summary>
            /// <returns>The verifier.</returns>
            /// <param name="password">Password.</param>
            public static Meteor.Verifier GenerateVerifier(string password, string identity = null, string salt = null)
            {
                if (identity == null)
                {
                    BigInteger i = new BigInteger();
                    i.genRandomBits(36);
                    identity = i.ToString(16).ToLowerInvariant().TrimStart('0');
                }

                if (salt == null)
                {
                    BigInteger s = new BigInteger();
                    s.genRandomBits(36);
                    salt = s.ToString(16).ToLowerInvariant().TrimStart('0');
                }

                string x = Hash(salt + Hash(identity + ":" + password));

                BigInteger xi = new BigInteger(x, 16);
                BigInteger v  = g.modPow(xi, N);

                return(new Meteor.Verifier()
                {
                    identity = identity,
                    salt = salt,
                    verifier = v.ToString(16).ToLowerInvariant().TrimStart('0')
                });
            }
        //подписываем сообщение
        public string SignGen(byte[] h, BigInteger d)
        {
            BigInteger alpha = new BigInteger(h);
            BigInteger e     = alpha % n;

            if (e == 0)
            {
                e = 1;
            }
            BigInteger k = new BigInteger();
            ECPoint    C = new ECPoint();
            BigInteger r = new BigInteger();
            BigInteger s = new BigInteger();

            do
            {
                do
                {
                    k.genRandomBits(n.bitCount(), new Random());
                } while ((k < 0) || (k > n));
                C = ECPoint.multiply(k, G);
                r = C.x % n;
                s = ((r * d) + (k * e)) % n;
            } while ((r == 0) || (s == 0));
            string Rvector = padding(r.ToHexString(), n.bitCount() / 4);
            string Svector = padding(s.ToHexString(), n.bitCount() / 4);

            return(Rvector + Svector);
        }
Ejemplo n.º 10
0
        public void TestGenCoPrime()
        {
            { // Test small values
                var bi  = new BigInteger();
                var rng = new RNGCryptoServiceProvider();

                bi.genRandomBits(100, rng);

                var coprime = bi.genCoPrime(10, rng);

                Assert.Equal(1, (bi.gcd(coprime)).getBytes()[0]);
            }

            // Test arbitrary values
            for (int i = 0; i < 99; i++)
            {
                var bi   = new BigInteger();
                var rng  = new RNGCryptoServiceProvider();
                var rand = new Random();

                bi.genRandomBits(rand.Next(1, 32 * 69 + 1), rng);

                var coprime = bi.genCoPrime(rand.Next(1, 2241), rng);

                Assert.Equal(1, (bi.gcd(coprime)).getBytes()[0]);
            }
        }
Ejemplo n.º 11
0
        protected override byte[] ProcessDataBlock(byte[] p_block)
        {
            // the random number, K
            BigInteger K;

            // create K, which is the random number
            do
            {
                K = new BigInteger();
                K.genRandomBits(o_key_struct.P.bitCount() - 1, o_random);
            } while (K.gcd(o_key_struct.P - 1) != 1);

            // compute the values A and B
            BigInteger A = o_key_struct.G.modPow(K, o_key_struct.P);
            BigInteger B = (o_key_struct.Y.modPow(K, o_key_struct.P)
                            * new BigInteger(p_block)) % (o_key_struct.P);

            // create an array to contain the ciphertext
            byte[] x_result = new byte[o_ciphertext_blocksize];
            // copy the bytes from A and B into the result array
            byte[] x_a_bytes = A.getBytes();
            Array.Copy(x_a_bytes, 0, x_result, o_ciphertext_blocksize / 2
                       - x_a_bytes.Length, x_a_bytes.Length);
            byte[] x_b_bytes = B.getBytes();
            Array.Copy(x_b_bytes, 0, x_result, o_ciphertext_blocksize
                       - x_b_bytes.Length, x_b_bytes.Length);
            // return the result array
            return(x_result);
        }
Ejemplo n.º 12
0
        public static byte[] CreateSignature(byte[] p_data, ElGamalKeyStruct p_key_struct)
        {
            BigInteger x_pminusone = p_key_struct.P - 1;
            BigInteger K;

            do
            {
                K = new BigInteger();
                K.genRandomBits(p_key_struct.P.bitCount() - 1, new Random());
            } while (K.gcd(x_pminusone) != 1);

            BigInteger A = p_key_struct.G.modPow(K, p_key_struct.P);
            BigInteger B = mod(mod(K.modInverse(x_pminusone) * (new BigInteger(p_data) - (p_key_struct.X * (A))), (x_pminusone)), (x_pminusone));

            byte[] x_a_bytes = A.getBytes();
            byte[] x_b_bytes = B.getBytes();

            int x_result_size = (((p_key_struct.P.bitCount() + 7) / 8) * 2);

            byte[] x_result = new byte[x_result_size];

            Array.Copy(x_a_bytes, 0, x_result, x_result_size / 2 - x_a_bytes.Length, x_a_bytes.Length);
            Array.Copy(x_b_bytes, 0, x_result, x_result_size - x_b_bytes.Length, x_b_bytes.Length);

            return(x_result);
        }
Ejemplo n.º 13
0
        private static BigInteger findRandomGenerator(BigInteger order, BigInteger modulo, Rng random)
        {
            BigInteger one = new BigInteger(1);
            BigInteger aux = modulo - new BigInteger(1);
            BigInteger t   = aux % order;
            BigInteger generator;

            if (t.LongValue() != 0)
            {
                return(null);
            }

            t = aux / order;

            while (true)
            {
                generator = new BigInteger();
                generator.genRandomBits(modulo.bitCount(), random);
                generator = generator % modulo;
                generator = generator.modPow(t, modulo);
                if (generator != one)
                {
                    break;
                }
            }

            aux = generator.modPow(order, modulo);

            if (aux != one)
            {
                return(null);
            }

            return(generator);
        }
        //функция вычисления квадратоного корня по модулю простого числа q
        public BigInteger ModSqrt(BigInteger a, BigInteger q)
        {
            BigInteger b = new BigInteger();

            do
            {
                b.genRandomBits(255, new Random());
            } while (Legendre(b, q) == 1);
            BigInteger s = 0;
            BigInteger t = q - 1;

            while ((t & 1) != 1)
            {
                s++;
                t = t >> 1;
            }
            BigInteger InvA = a.modInverse(q);
            BigInteger c    = b.modPow(t, q);
            BigInteger r    = a.modPow(((t + 1) / 2), q);
            BigInteger d    = new BigInteger();

            for (int i = 1; i < s; i++)
            {
                BigInteger temp = 2;
                temp = temp.modPow((s - i - 1), q);
                d    = (r.modPow(2, q) * InvA).modPow(temp, q);
                if (d == (q - 1))
                {
                    r = (r * c) % q;
                }
                c = c.modPow(2, q);
            }
            return(r);
        }
Ejemplo n.º 15
0
        public RSA_Sign()
        {
            Random uy = new Random();

            BigInteger p = BigInteger.genPseudoPrime(129, 13, uy);
            BigInteger q = BigInteger.genPseudoPrime(128, 13, uy);

            n = p * q;
            p--;
            q--;
            BigInteger w = p * q;

            e = new BigInteger();
            BigInteger one = new BigInteger(1);

            do
            {
ar:
                e.genRandomBits(256, uy);
                if (e > n)
                {
                    goto ar;
                }
            }while (BigInteger.NOD(e, w) != one);
            // d - закрытый ключ (обратный к е по модулю w)
            d = BigInteger.Inverse(e, w);
        }
Ejemplo n.º 16
0
        public void TestGenCoPrime()
        {
            { // Test small values
                var bi  = new BigInteger();
                var rng = new RNGCryptoServiceProvider();

                bi.genRandomBits(100, rng);

                var coprime = bi.genCoPrime(10, rng);

                Assert.IsTrue((bi.gcd(coprime)).getBytes()[0] == 1);
            }

            { // Test arbitrary values
                var bi   = new BigInteger();
                var rng  = new RNGCryptoServiceProvider();
                var rand = new Random();

                bi.genRandomBits(rand.Next(2241), rng);

                var coprime = bi.genCoPrime(rand.Next(2241), rng);

                Assert.IsTrue((bi.gcd(coprime)).getBytes()[0] == 1);
            }
        }
Ejemplo n.º 17
0
        public BigInteger PrivateKeyToSalt(byte[] PrivateData)
        {
            BigInteger bigInt = new BigInteger();

            int seed = 0x0FFFFAAA;

            for (int i = 0; i < (PrivateData.Length / 4) - 1; i++)
            {
                seed += BitConverter.ToInt32(PrivateData, i * 4);
            }

            bigInt.genRandomBits(128, new Random(seed));

            BigInteger temp = seed;

            for (int i = 0; i < PrivateData.Length / 8; i++)
            {
                if ((i * 8) + 8 > PrivateData.Length)
                {
                    break;
                }

                bigInt += temp >> 8;
                temp   += equK(bigInt, temp + BitConverter.ToUInt64(PrivateData, i * 8), seed);
                bigInt += temp;
            }

            return(bigInt);
        }
Ejemplo n.º 18
0
 //функция вычисления квадратоного корня по модулю простого числа q
 public BigInteger ModSqrt(BigInteger a, BigInteger q)
 {
     BigInteger b = new BigInteger();
     do
     {
         b.genRandomBits(255, new Random());
     } while (Legendre(b, q) == 1);
     BigInteger s = 0;
     BigInteger t = q - 1;
     while ((t & 1) != 1)
     {
         s++;
         t = t >> 1;
     }
     BigInteger InvA = a.modInverse(q);
     BigInteger c = b.modPow(t, q);
     BigInteger r = a.modPow(((t + 1) / 2), q);
     BigInteger d = new BigInteger();
     for (int i = 1; i < s; i++)
     {
         BigInteger temp = 2;
         temp = temp.modPow((s - i - 1), q);
         d = (r.modPow(2, q) * InvA).modPow(temp, q);
         if (d == (q - 1))
             r = (r * c) % q;
         c = c.modPow(2, q);
     }
     return r;
 }
Ejemplo n.º 19
0
        public void TestRandomBI()
        {
            // Failed test because of zeroes

            ElGamal algorithm = new ElGamalManaged();

            algorithm.Padding = ElGamalPaddingMode.LeadingZeros;

            for (algorithm.KeySize = 384; algorithm.KeySize <= 1088; algorithm.KeySize += 8)
            {
                ElGamal encryptAlgorithm = new ElGamalManaged();
                encryptAlgorithm.FromXmlString(algorithm.ToXmlString(false));

                ElGamal decryptAlgorithm = new ElGamalManaged();
                decryptAlgorithm.FromXmlString(algorithm.ToXmlString(true));

                var z = new BigInteger();
                z.genRandomBits(new Random().Next(1, 2241), new RNGCryptoServiceProvider());

                var z_enc = encryptAlgorithm.EncryptData(z.getBytes());
                var z_dec = decryptAlgorithm.DecryptData(z_enc);

                CollectionAssert.AreEqual(z.getBytes(), z_dec);
            }
        }
Ejemplo n.º 20
0
 //Генерируем секретный ключ заданной длины
 public BigInteger GenPrivateKey(int BitSize)
 {
     BigInteger d = new BigInteger();
     do
     {
         d.genRandomBits(BitSize, new Random());
     } while ((d < 0) || (d > n));
     return d;
 }
Ejemplo n.º 21
0
        internal void CalculatePasswordHash(string password)
        {
            BigInteger sTemp = new BigInteger();

            sTemp.genRandomBits(256, new Random((int)DateTime.Now.Ticks));
            _s = sTemp.ToString();
            _x = new BigInteger(Utils.Hash(_s + password));
            _v = g.modPow(_x, _N);
        }
Ejemplo n.º 22
0
            static SRP()
            {
                // initialize N
                {
                    NHex =
                        //512bit
                        //"D4C7F8A2B32C11B8FBA9581EC4BA4F1B04215642EF7355E37C0FC0443EF756EA2C6B8EEB755A1C723027663CAA265EF785B8FF6A9B35227A52D86633DBDFCA43";
                        //256bit
                        "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE48E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B297BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9AFD5138FE8376435B9FC61D2FC0EB06E3".ToLowerInvariant();
                    N       = new BigInteger(NHex, 16);
                    _nbits  = N.bitCount();
                    Nminus1 = N - 1;

//                    if (!N.isProbablePrime(80))
//                    {
//                        throw new Exception("Warning: N is not prime");
//                    }
//
//                    if (!(Nminus1 / 2).isProbablePrime(80))
//                    {
//                        throw new Exception("Warning: (N-1)/2 is not prime");
//                    }
                }

                // initialize g
                {
                    gHex = "2";
                    g    = new BigInteger(gHex, 16);
                }

                // initialize k = H(N || g)
                {
                    BigInteger ktmp = new BigInteger(HHex(
                                                         (((NHex.Length & 1) == 0) ? "" : "0") + NHex +
                                                         new string('0', NHex.Length - gHex.Length) + gHex
                                                         ), 16);

                    k    = (ktmp < N) ? ktmp : (ktmp % N);
                    kHex = k.ToString(16).ToLowerInvariant().TrimStart('0');
                }

                // initialize a, A
                {
                    a = new BigInteger();
                    a.genRandomBits(36);
                    A = g.modPow(a, N);

                    while (A.modInverse(N) == 0)
                    {
                        a = new BigInteger();
                        a.genRandomBits(36);
                        A = g.modPow(a, N);
                    }
                    Ahex = A.ToString(16).ToLowerInvariant().TrimStart('0');
                }
            }
        //Генерируем секретный ключ заданной длины
        public BigInteger GenPrivateKey(int BitSize)
        {
            BigInteger d = new BigInteger();

            do
            {
                d.genRandomBits(BitSize, new Random());
            } while ((d < 0) || (d > n));
            return(d);
        }
Ejemplo n.º 24
0
        //генерация секретного ключа заданной длины.
        public BigInteger GenPrivateKey(int bitSize)
        {
            var result = new BigInteger();

            do
            {
                result.genRandomBits(bitSize, new Random());
            } while (result < 0 || result > _n);

            return(result);
        }
Ejemplo n.º 25
0
            public static void AuthStep1(
                string vHex,
                string AHex,
                out string bHex,
                out string BHex,
                out string uHex)
            {
                BigInteger v = new BigInteger(vHex, 16);
                BigInteger A = new BigInteger(AHex, 16);

                BigInteger b;

                // b - ephemeral private key
                // b = random between 2 and N-1
                {
                    b = new BigInteger();
                    //[TODO] perhaps here use a better random generator
                    b.genRandomBits(_nbits, new Random((int)DateTime.Now.Ticks));

                    if (b >= N)
                    {
                        b = b % Nminus1;
                    }
                    if (b < 2)
                    {
                        b = 2;
                    }
                }
                bHex = b.ToHexString();

                // B = public key
                // B = kv + g^b (mod N)
                BigInteger B = (v * k + g.modPow(b, N)) % N;

                BHex = B.ToHexString();

                BigInteger u;

                // u - scrambling parameter
                // u = H (A || B)
                {
                    int nlen = 2 * ((_nbits + 7) >> 3);

                    BigInteger utmp = new BigInteger(HHex(
                                                         new string('0', nlen - AHex.Length) + AHex +
                                                         new string('0', nlen - BHex.Length) + BHex
                                                         ), 16);

                    u = (utmp < N) ? utmp : (utmp % Nminus1);
                }

                uHex = u.ToHexString();
            }
Ejemplo n.º 26
0
        /// <summary>
        /// Adds padding to the input data and returns the padded data.
        /// </summary>
        /// <param name="dataBytes">Data to be padded prior to encryption</param>
        /// <param name="params">RSA Parameters used for padding computation</param>
        /// <returns>Padded message</returns>
        public byte[] EncodeMessage(byte[] dataBytes, RSAParameters @params)
        {
            //Determine if we can add padding.
            if (dataBytes.Length > GetMaxMessageLength(@params))
            {
                throw new CryptographicException("Data length is too long.  Increase your key size or consider encrypting less data.");
            }

            int        padLength = @params.N.Length - dataBytes.Length - 3;
            BigInteger biRnd     = new BigInteger();

            biRnd.genRandomBits(padLength * 8, new Random(DateTime.Now.Millisecond));

            byte[] bytRandom = null;
            bytRandom = biRnd.getBytes();

            int z1 = bytRandom.Length;

            //Make sure the bytes are all > 0.
            for (int i = 0; i <= bytRandom.Length - 1; i++)
            {
                if (bytRandom[i] == 0x00)
                {
                    bytRandom[i] = 0x01;
                }
            }

            byte[] result = new byte[@params.N.Length];


            //Add the starting 0x00 byte
            result[0] = 0x00;

            //Add the version code 0x02 byte
            result[1] = 0x02;

            for (int i = 0; i <= bytRandom.Length - 1; i++)
            {
                z1         = i + 2;
                result[z1] = bytRandom[i];
            }

            //Add the trailing 0 byte after the padding.
            result[bytRandom.Length + 2] = 0x00;

            //This starting index for the unpadded data.
            int idx = bytRandom.Length + 3;

            //Copy the unpadded data to the padded byte array.
            dataBytes.CopyTo(result, idx);

            return(result);
        }
Ejemplo n.º 27
0
        public bignum rand( Random randg )
        {
            BigInteger b = this.value;
               int numBits = b.bitCount();
               BigInteger x = new BigInteger();
               x.genRandomBits( numBits, randg );

               if (x > b)
              return new bignum(x % b);
               else
              return new bignum(x);
        }
Ejemplo n.º 28
0
        private static BigInteger GetRandomBigInteger(BigInteger p)
        {
            BigInteger randomNumber = null;

            while ((object)randomNumber == null || randomNumber >= p)
            {
                var random = new Random();
                randomNumber = new BigInteger();
                randomNumber.genRandomBits(256, random);
            }

            return(randomNumber);
        }
Ejemplo n.º 29
0
    public static BigInteger genPseudoPrime(int bits, int confidence, Random rand)
    {
        BigInteger result = new BigInteger();
        bool       done   = false;

        while (!done)
        {
            result.genRandomBits(bits, rand);
            result.data[0] |= 0x01;             // make it odd

            // prime test
            done = result.isProbablePrime(confidence);
        }
        return(result);
    }
Ejemplo n.º 30
0
        // TODO: check again for encryption
        protected override byte[] ProcessDataBlock(byte[] p_block)
        {
            //// set random K
            //BigInteger K;
            //do
            //{
            //    K = new BigInteger();
            //    K.genRandomBits(o_key_struct.P.bitCount() - 1, o_random);
            //} while (K.gcd(o_key_struct.P - 1) != 1);

            //// compute the values A and B
            //BigInteger A = o_key_struct.G.modPow(K, o_key_struct.P);
            //BigInteger B = (o_key_struct.Y.modPow(K, o_key_struct.P) * new BigInteger(p_block)) % (o_key_struct.P);

            //// create an array to contain the ciphertext
            //byte[] x_result = new byte[o_ciphertext_blocksize];
            //// copy the bytes from A and B into the result array
            //byte[] x_a_bytes = A.getBytes();
            //Array.Copy(x_a_bytes, 0, x_result, o_ciphertext_blocksize / 2
            //    - x_a_bytes.Length, x_a_bytes.Length);
            //byte[] x_b_bytes = B.getBytes();
            //Array.Copy(x_b_bytes, 0, x_result, o_ciphertext_blocksize
            //    - x_b_bytes.Length, x_b_bytes.Length);
            //// return the result array
            //return x_result;

            // *********** SPECIAL ************ //

            // generate random R
            BigInteger R = new BigInteger();

            R.genRandomBits(o_key_struct.N.bitCount() - 1, o_random); //R's bitlength is n-1 so that r is within Zn

            // ciphertext c = g^m * r^n mod n^2
            BigInteger Nsquare = o_key_struct.N * o_key_struct.N;
            BigInteger C       = (o_key_struct.G.modPow(new BigInteger(p_block), Nsquare)
                                  * R.modPow(o_key_struct.N, Nsquare)) % Nsquare;

            // create an array to contain the ciphertext
            byte[] x_result = new byte[o_ciphertext_blocksize];
            byte[] c_bytes  = C.getBytes();

            // copy c_bytes into x_result
            Array.Copy(c_bytes, 0, x_result, o_ciphertext_blocksize - c_bytes.Length, c_bytes.Length);

            // return result array
            return(x_result);
        }
Ejemplo n.º 31
0
        public static DSAKeyPair GenerateNew(int bits, Rng random) {
            BigInteger one = new BigInteger(1);
            BigInteger[] pq = findRandomStrongPrime((uint)bits, 160, random);
            BigInteger p = pq[0], q = pq[1];
            BigInteger g = findRandomGenerator(q, p, random);

            BigInteger x;
            do {
                x = new BigInteger();
                x.genRandomBits(q.bitCount(), random);
            } while ((x < one) || (x > q));

            BigInteger y = g.modPow(x, p);

            return new DSAKeyPair(p, g, q, y, x);
        }
Ejemplo n.º 32
0
        public string KeyChallengeResponse1(string userName, int securityLevel)
        {
            BigInteger scTemp = new BigInteger();

            scTemp.genRandomBits(256, new Random((int)DateTime.Now.Ticks));
            sc = scTemp.ToString().ToLower();

            KPRPCMessage data2client = new KPRPCMessage();

            data2client.protocol          = "setup";
            data2client.key               = new KeyParams();
            data2client.key.sc            = sc;
            data2client.key.securityLevel = securityLevel;
            data2client.version           = ProtocolVersion;
            data2client.features          = features;

            string response = Jayrock.Json.Conversion.JsonConvert.ExportToString(data2client);

            return(response);
        }
Ejemplo n.º 33
0
        public static DSAKeyPair GenerateNew(int bits, Rng random)
        {
            BigInteger one = new BigInteger(1);

            BigInteger[] pq = findRandomStrongPrime((uint)bits, 160, random);
            BigInteger   p = pq[0], q = pq[1];
            BigInteger   g = findRandomGenerator(q, p, random);

            BigInteger x;

            do
            {
                x = new BigInteger();
                x.genRandomBits(q.bitCount(), random);
            } while ((x < one) || (x > q));

            BigInteger y = g.modPow(x, p);

            return(new DSAKeyPair(p, g, q, y, x));
        }
Ejemplo n.º 34
0
        //подписываем сообщение
        // msg - сообщение
        // d - ключ подписи
        public string SingMsg(byte[] msg, BigInteger d)
        {
            // Шаг 2: вычислить e
            BigInteger e = new BigInteger(msg) % q;

            if (e == 0)
            {
                e = 1;
            }

            BigInteger k = new BigInteger();
            // точка эллиптической кривой
            ECPoint C = new ECPoint();

            BigInteger r = new BigInteger();
            BigInteger s = new BigInteger();

            do
            {
                // Шаг 3: сгенерировать случайное k (0< k <q)
                do
                {
                    k.genRandomBits(q.bitCount(), new Random());
                } while ((k < 0) || (k > q));

                // найти точку элл. C = kP
                C = ECPoint.multiply(k, Q);
                // и определить r = Xc(mod q)
                r = C.x % q;
                // определим s = (rd + ke)(mod q), s == 0 -> Шаг 3
                s = ((r * d) + (k * e)) % q;
            } while ((r == 0) || (s == 0));

            // перевод значений в двоичный вид
            string Rvector = padding(r.ToHexString(), q.bitCount() / 4);

            string Svector = padding(s.ToHexString(), q.bitCount() / 4);

            // конкатенацию двух двоичных векторов  (цифровая подпись)
            return(Rvector + Svector);
        }
Ejemplo n.º 35
0
        private static BigInteger findRandomGenerator(BigInteger order, BigInteger modulo, Random random)
        {
            BigInteger one = new BigInteger(1);
            BigInteger aux = modulo - new BigInteger(1);
            BigInteger t   = aux % order;
            BigInteger generator;

            if(t.LongValue() != 0) {
                return null;
            }

            t = aux / order;

            while(true) {
                generator = new BigInteger();
                generator.genRandomBits(modulo.bitCount(), random);
                generator = generator % modulo;
                generator = generator.modPow(t, modulo);
                if(generator!=one)
                    break;
            }

            aux = generator.modPow(order, modulo);

            if(aux!=one) {
                return null;
            }

            return generator;
        }
Ejemplo n.º 36
0
 //Генерируем секретный ключ заданной длины
 public BigInteger GenPrivateKey(int BitSize, int Seed)
 {
     BigInteger d = new BigInteger();
     int count = 0;
     do
     {
         d.genRandomBits(BitSize, new Random(Seed * 100000 * count));
         count++;
     } while ((d < 0) || (d > n));
     return d;
 }
Ejemplo n.º 37
0
        //***********************************************************************
        // Tests the correct implementation of sqrt() method.
        //***********************************************************************

        public static void SqrtTest(int rounds)
        {
                Random rand = new Random();
	        for(int count = 0; count < rounds; count++)
	        {
	                // generate data of random length
		        int t1 = 0;
		        while(t1 == 0)
			        t1 = (int)(rand.NextDouble() * 1024);

                        Console.Write("Round = " + count);

                        BigInteger a = new BigInteger();
                        a.genRandomBits(t1, rand);

                        BigInteger b = a.sqrt();
                        BigInteger c = (b+1)*(b+1);

                        // check that b is the largest integer such that b*b <= a
                        if(c <= a)
	        	{
		        	Console.WriteLine("\nError at round " + count);
                                Console.WriteLine(a + "\n");
			        return;
		        }
		        Console.WriteLine(" <PASSED>.");
	        }
        }
Ejemplo n.º 38
0
        //***********************************************************************
        // Generates a random number with the specified number of bits such
        // that gcd(number, this) = 1
        //***********************************************************************

        public BigInteger genCoPrime(int bits, Random rand)
        {
	        bool done = false;
	        BigInteger result = new BigInteger();

	        while(!done)
	        {
	                result.genRandomBits(bits, rand);
	                //Console.WriteLine(result.ToString(16));

		        // gcd test
		        BigInteger g = result.gcd(this);
			if(g.dataLength == 1 && g.data[0] == 1)
                                done = true;
	        }

	        return result;
        }
Ejemplo n.º 39
0
        //***********************************************************************
        // Generates a positive BigInteger that is probably prime.
        //***********************************************************************

        public static BigInteger genPseudoPrime(int bits, int confidence, Random rand)
        {
	        BigInteger result = new BigInteger();
	        bool done = false;

	        while(!done)
	        {
		        result.genRandomBits(bits, rand);
		        result.data[0] |= 0x01;		// make it odd

		        // prime test
		        done = result.isProbablePrime(confidence);
	        }
	        return result;
        }
Ejemplo n.º 40
0
        //***********************************************************************
        // Probabilistic prime test based on Solovay-Strassen (Euler Criterion)
        //
        // p is probably prime if for any a < p (a is not multiple of p),
        // a^((p-1)/2) mod p = J(a, p)
        //
        // where J is the Jacobi symbol.
        //
        // Otherwise, p is composite.
        //
        // Returns
        // -------
        // True if "this" is a Euler pseudoprime to randomly chosen
        // bases.  The number of chosen bases is given by the "confidence"
        // parameter.
        //
        // False if "this" is definitely NOT prime.
        //
        //***********************************************************************

        public bool SolovayStrassenTest(int confidence)
        {
                BigInteger thisVal;
                if((this.data[maxLength-1] & 0x80000000) != 0)        // negative
                        thisVal = -this;
                else
                        thisVal = this;

                if(thisVal.dataLength == 1)
                {
                        // test small numbers
                        if(thisVal.data[0] == 0 || thisVal.data[0] == 1)
                                return false;
                        else if(thisVal.data[0] == 2 || thisVal.data[0] == 3)
                                return true;
                }

                if((thisVal.data[0] & 0x1) == 0)     // even numbers
                        return false;


	        int bits = thisVal.bitCount();
	        BigInteger a = new BigInteger();
	        BigInteger p_sub1 = thisVal - 1;
	        BigInteger p_sub1_shift = p_sub1 >> 1;

	        Random rand = new Random();

	        for(int round = 0; round < confidence; round++)
	        {
		        bool done = false;

		        while(!done)		// generate a < n
		        {
			        int testBits = 0;

			        // make sure "a" has at least 2 bits
			        while(testBits < 2)
				        testBits = (int)(rand.NextDouble() * bits);

			        a.genRandomBits(testBits, rand);

			        int byteLen = a.dataLength;

                                // make sure "a" is not 0
			        if(byteLen > 1 || (byteLen == 1 && a.data[0] != 1))
				        done = true;
		        }

                        // check whether a factor exists (fix for version 1.03)
		        BigInteger gcdTest = a.gcd(thisVal);
                        if(gcdTest.dataLength == 1 && gcdTest.data[0] != 1)
                                return false;

		        // calculate a^((p-1)/2) mod p

		        BigInteger expResult = a.modPow(p_sub1_shift, thisVal);
		        if(expResult == p_sub1)
		                expResult = -1;

                        // calculate Jacobi symbol
                        BigInteger jacob = Jacobi(a, thisVal);

                        //Console.WriteLine("a = " + a.ToString(10) + " b = " + thisVal.ToString(10));
                        //Console.WriteLine("expResult = " + expResult.ToString(10) + " Jacob = " + jacob.ToString(10));

                        // if they are different then it is not prime
                        if(expResult != jacob)
			        return false;
	        }

	        return true;
        }
Ejemplo n.º 41
0
        //***********************************************************************
        // Probabilistic prime test based on Rabin-Miller's
        //
        // for any p > 0 with p - 1 = 2^s * t
        //
        // p is probably prime (strong pseudoprime) if for any a < p,
        // 1) a^t mod p = 1 or
        // 2) a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1
        //
        // Otherwise, p is composite.
        //
        // Returns
        // -------
        // True if "this" is a strong pseudoprime to randomly chosen
        // bases.  The number of chosen bases is given by the "confidence"
        // parameter.
        //
        // False if "this" is definitely NOT prime.
        //
        //***********************************************************************

        public bool RabinMillerTest(int confidence)
        {
                BigInteger thisVal;
                if((this.data[maxLength-1] & 0x80000000) != 0)        // negative
                        thisVal = -this;
                else
                        thisVal = this;

                if(thisVal.dataLength == 1)
                {
                        // test small numbers
                        if(thisVal.data[0] == 0 || thisVal.data[0] == 1)
                                return false;
                        else if(thisVal.data[0] == 2 || thisVal.data[0] == 3)
                                return true;
                }

                if((thisVal.data[0] & 0x1) == 0)     // even numbers
                        return false;


                // calculate values of s and t
                BigInteger p_sub1 = thisVal - (new BigInteger(1));
                int s = 0;

                for(int index = 0; index < p_sub1.dataLength; index++)
                {
                        uint mask = 0x01;

                        for(int i = 0; i < 32; i++)
                        {
                                if((p_sub1.data[index] & mask) != 0)
                                {
                                        index = p_sub1.dataLength;      // to break the outer loop
                                        break;
                                }
                                mask <<= 1;
                                s++;
                        }
                }

                BigInteger t = p_sub1 >> s;

	        int bits = thisVal.bitCount();
	        BigInteger a = new BigInteger();
	        Random rand = new Random();

	        for(int round = 0; round < confidence; round++)
	        {
		        bool done = false;

		        while(!done)		// generate a < n
		        {
			        int testBits = 0;

			        // make sure "a" has at least 2 bits
			        while(testBits < 2)
				        testBits = (int)(rand.NextDouble() * bits);

			        a.genRandomBits(testBits, rand);

			        int byteLen = a.dataLength;

                                // make sure "a" is not 0
			        if(byteLen > 1 || (byteLen == 1 && a.data[0] != 1))
				        done = true;
		        }

                        // check whether a factor exists (fix for version 1.03)
		        BigInteger gcdTest = a.gcd(thisVal);
                        if(gcdTest.dataLength == 1 && gcdTest.data[0] != 1)
                                return false;

                        BigInteger b = a.modPow(t, thisVal);

                        /*
                        Console.WriteLine("a = " + a.ToString(10));
                        Console.WriteLine("b = " + b.ToString(10));
                        Console.WriteLine("t = " + t.ToString(10));
                        Console.WriteLine("s = " + s);
                        */

                        bool result = false;

                        if(b.dataLength == 1 && b.data[0] == 1)         // a^t mod p = 1
                                result = true;

                        for(int j = 0; result == false && j < s; j++)
                        {
                                if(b == p_sub1)         // a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1
                                {
                                        result = true;
                                        break;
                                }

                                b = (b * b) % thisVal;
                        }

                        if(result == false)
                                return false;
                }
	        return true;
        }
Ejemplo n.º 42
0
        //***********************************************************************
        // Probabilistic prime test based on Fermat's little theorem
        //
        // for any a < p (p does not divide a) if
        //      a^(p-1) mod p != 1 then p is not prime.
        //
        // Otherwise, p is probably prime (pseudoprime to the chosen base).
        //
        // Returns
        // -------
        // True if "this" is a pseudoprime to randomly chosen
        // bases.  The number of chosen bases is given by the "confidence"
        // parameter.
        //
        // False if "this" is definitely NOT prime.
        //
        // Note - this method is fast but fails for Carmichael numbers except
        // when the randomly chosen base is a factor of the number.
        //
        //***********************************************************************

        public bool FermatLittleTest(int confidence)
        {
                BigInteger thisVal;
                if((this.data[maxLength-1] & 0x80000000) != 0)        // negative
                        thisVal = -this;
                else
                        thisVal = this;

                if(thisVal.dataLength == 1)
                {
                        // test small numbers
                        if(thisVal.data[0] == 0 || thisVal.data[0] == 1)
                                return false;
                        else if(thisVal.data[0] == 2 || thisVal.data[0] == 3)
                                return true;
                }

                if((thisVal.data[0] & 0x1) == 0)     // even numbers
                        return false;

	        int bits = thisVal.bitCount();
	        BigInteger a = new BigInteger();
	        BigInteger p_sub1 = thisVal - (new BigInteger(1));
	        Random rand = new Random();

	        for(int round = 0; round < confidence; round++)
	        {
		        bool done = false;

		        while(!done)		// generate a < n
		        {
			        int testBits = 0;

			        // make sure "a" has at least 2 bits
			        while(testBits < 2)
				        testBits = (int)(rand.NextDouble() * bits);

			        a.genRandomBits(testBits, rand);

			        int byteLen = a.dataLength;

                                // make sure "a" is not 0
			        if(byteLen > 1 || (byteLen == 1 && a.data[0] != 1))
                                        done = true;
		        }

                        // check whether a factor exists (fix for version 1.03)
		        BigInteger gcdTest = a.gcd(thisVal);
                        if(gcdTest.dataLength == 1 && gcdTest.data[0] != 1)
                                return false;

		        // calculate a^(p-1) mod p
		        BigInteger expResult = a.modPow(p_sub1, thisVal);

		        int resultLen = expResult.dataLength;

                        // is NOT prime is a^(p-1) mod p != 1

		        if(resultLen > 1 || (resultLen == 1 && expResult.data[0] != 1))
		        {
		                //Console.WriteLine("a = " + a.ToString());
			        return false;
                        }
	        }

	        return true;
        }
Ejemplo n.º 43
0
        //формирование цифровой подписи.
        public string genDS(byte[] h, BigInteger d)
        {
            BigInteger a = new BigInteger(h);
            BigInteger e = a % n;
            if (e == 0)
                e = 1;
            BigInteger k = new BigInteger();
            CECPoint C=new CECPoint();
            BigInteger r=new BigInteger();
            BigInteger s = new BigInteger();
            do
            {
                do
                {
                    k.genRandomBits(n.bitCount(), new Random());
                } 
                while ((k < 0) || (k > n));

                C = CECPoint.multiply(G, k);
                r = C.x % n;
                s = ((r * d) + (k * e)) % n;
            } 
            while ((r == 0)||(s==0));

            string Rvector = padding(r.ToHexString(), n.bitCount() / 4);
            string Svector = padding(s.ToHexString(), n.bitCount() / 4);
            return Rvector + Svector;
        }
Ejemplo n.º 44
0
 //подписываем сообщение
 public string SignGen(byte[] h, BigInteger d)
 {
     alpha = new BigInteger(h);
     e = alpha % n;
     if (e == 0)
         e = 1;
     k = new BigInteger();
     C = new ECPoint();
     r = new BigInteger();
     s = new BigInteger();
     do
     {
         do
         {
             k.genRandomBits(n.bitCount(), new Random());
         } while ((k < 0) || (k > n));
         C = ECPoint.multiply(k, G);
         r = C.x % n;
         s = ((r * d) + (k * e)) % n;
     } while ((r == 0) || (s == 0));
     string Rvector = padding(r.ToHexString(), n.bitCount() / 4);
     string Svector = padding(s.ToHexString(), n.bitCount() / 4);
     return Rvector + Svector;
 }
Ejemplo n.º 45
0
        // TODO redesign keep strategy to allow keeping both highest and lowest
        private static BigInteger roll(BigInteger dieType, long dieCount, long keepCount, KeepStrategy keepStrategy)
        {
            if (dieType <= 1) {
                throw new InvalidExpressionException ("invalid die");
            }

            // if the diecount is negative we will roll with the positive diecount, but negate the end result.
            // basically, "-5d6" is treated as "-(5d6)"
            bool negative = false;
            if (dieCount < 0) {
                negative = true;
                dieCount = -dieCount;
            }

            keepCount = Math.Min(keepCount, dieCount);

            // roll the dice and keep them in an array
            BigInteger[] results = new BigInteger[dieCount];
            for (int i = 0; i < dieCount; i++) {
                BigInteger num = new BigInteger ();
                num.genRandomBits (dieType.bitCount (), RAND);
                results [i] = num;
            }

            // add up the results based on the strategy used
            BigInteger result = 0;
            if (keepStrategy == KeepStrategy.ALL) {
                for (int i = 0; i < dieCount; i++) {
                    result += results [i];
                }
            } else { // we are only keeping some, so sort the list
                Array.Sort (results);
                if (keepStrategy == KeepStrategy.HIGHEST) {
                    for (long i = dieCount - 1; i >= dieCount - keepCount; i--) {
                        result += results [i];
                    }
                } else if (keepStrategy == KeepStrategy.LOWEST) {
                    for (int i = 0; i < keepCount; i++) {
                        result += results [i];
                    }
                }
            }
            if (negative) {
                result = -result;
            }
            return result;
        }
Ejemplo n.º 46
0
            /// <summary>
            /// Adds padding to the input data and returns the padded data.
            /// </summary>
            /// <param name="dataBytes">Data to be padded prior to encryption</param>
            /// <param name="parameters">RSA Parameters used for padding computation</param>
            /// <returns>Padded message</returns>
            public byte[] EncodeMessage( byte[] dataBytes, RSAParameters parameters )
            {
                //Determine if we can add padding.
                if( dataBytes.Length > GetMaxMessageLength( parameters ) ) {
                    throw new Exception( "Data length is too long. Increase your key size or consider encrypting less data." );
                }

                int padLength = parameters.N.Length - dataBytes.Length - 3;
                BigInteger biRnd = new BigInteger();
                biRnd.genRandomBits( padLength * 8, new Random( DateTime.Now.Millisecond ) );

                byte[] bytRandom = null;
                bytRandom = biRnd.getBytes();

                int z1 = bytRandom.Length;

                //Make sure the bytes are all > 0.
                for( int i = 0; i <= bytRandom.Length - 1; i++ ) {
                    if( bytRandom[i] == 0x00 ) {
                        bytRandom[i] = 0x01;
                    }
                }

                byte[] result = new byte[parameters.N.Length];

                //Add the starting 0x00 byte
                result[0] = 0x00;

                //Add the version code 0x02 byte
                result[1] = 0x02;

                for( int i = 0; i <= bytRandom.Length - 1; i++ ) {
                    z1 = i + 2;
                    result[z1] = bytRandom[i];
                }

                //Add the trailing 0 byte after the padding.
                result[bytRandom.Length + 2] = 0x00;

                //This starting index for the unpadded data.
                int idx = bytRandom.Length + 3;

                //Copy the unpadded data to the padded byte array.
                dataBytes.CopyTo( result, idx );

                return result;
            }
Ejemplo n.º 47
0
    public static void GenerateRSAKey(int moduleBitLen, int pubKeyBitLen, out BigInteger publicExponent, out BigInteger module, out BigInteger privateExponent)
    {
        /* from Wikipedia:
        RSA involves a public key and a private key. The public key can be known to everyone and is used for encrypting messages. Messages encrypted with the public key can only be decrypted using the private key. The keys for the RSA algorithm are generated the following way:
        Choose two distinct prime numbers p and q.
        For security purposes, the integers p and q should be chosen at random, and should be of similar bit-length. Prime integers can be efficiently found using a primality test.
        Compute n = pq.
        n is used as the modulus for both the public and private keys
        Compute φ(n) = (p – 1)(q – 1), where φ is Euler's totient function.
        Choose an integer e such that 1 < e < φ(n) and greatest common divisor of (e, φ(n)) = 1; i.e., e and φ(n) are coprime.
        e is released as the public key exponent.
        e having a short bit-length and small Hamming weight results in more efficient encryption - most commonly 0x10001 = 65,537. However, small values of e (such as 3) have been shown to be less secure in some settings.[4]
        Determine d as:
        d = e^-1 (mod φ(n))

        i.e., d is the multiplicative inverse of e mod φ(n).
        This is more clearly stated as solve for d given (de) mod φ(n) = 1
        This is often computed using the extended Euclidean algorithm.
        d is kept as the private key exponent.
         * */
        Random r = new Random();
        BigInteger P = new BigInteger();
        BigInteger Q = new BigInteger();
        int bitLenP = moduleBitLen >> 1;
        int bitLenQ = bitLenP + (moduleBitLen & 1);
        while (true)
        {
            while (true)
            {
                P.genRandomBits(bitLenP, r);
                P.data[0] |= 0x01;		// make it odd
                if (P.isProbablePrime())
                    break;
            }
            while (true)
            {
                Q.genRandomBits(bitLenQ, r);
                Q.data[0] |= 0x01;		// make it odd
                if (Q.isProbablePrime())
                    break;
            }
            var N = P * Q;
            var PHI = (P - 1) * (Q - 1);
            var E = PHI.genCoPrime(pubKeyBitLen,r);
            BigInteger D = E.modInverse(PHI);
            publicExponent = E;
            privateExponent = D;
            module = N;
            return;
        }
    }
Ejemplo n.º 48
0
 public static BigInteger Random(int BitCount)
 {
 	Random rand = new Random(Environment.TickCount);
 	BigInteger b = new BigInteger();
 	b.genRandomBits(BitCount, rand);
 	return b;
 }
Ejemplo n.º 49
0
    // secret shares an input based on n,r parameters
    public SharedData[] ShareData( long secret)
    {
        BigInteger[] coefficients = new BigInteger[numNecessaryParts - 1];
        BigInteger[] toReturn_p = new BigInteger[numAllParts];

        for (int i = 0; i < numNecessaryParts - 1; i++)
        {
            BigInteger a = new BigInteger();
            a.genRandomBits(64, new Random());
            a = a.abs() % modP;
            coefficients[i] = a;

        }

        for (long i = 0; i < numAllParts; i++)
        {
            toReturn_p[i] = 0;

            for (long j = 0; j < numNecessaryParts - 1; j++)
            {

                BigInteger tmp = new BigInteger((long)(Math.Pow(i + 1, j + 1)));

                toReturn_p[i] = (toReturn_p[i] + (BigInteger)(coefficients[j] * tmp)) % modP;
            }

        }

        SharedData[] toReturn = new SharedData[numAllParts];

        for (int i = 0; i < numAllParts; i++)
        {
            toReturn_p[i] = (toReturn_p[i] + new BigInteger(secret)) % modP;
            toReturn[i].yi = toReturn_p[i].LongValue();
            toReturn[i].xi = i + 1;
        }

        return toReturn;
    }
Ejemplo n.º 50
0
        private static BigInteger[] findRandomStrongPrime(uint primeBits, int orderBits,	Random random)
        {
            BigInteger one = new BigInteger(1);
            BigInteger u, aux, aux2;
            long[] table_q, table_u, prime_table;
            PrimeSieve sieve = new PrimeSieve(16000);
            uint table_count  = sieve.AvailablePrimes() - 1;
            int i, j;
            bool flag;
            BigInteger prime = null, order = null;

            order = BigInteger.genPseudoPrime(orderBits, 20, random);

            prime_table = new long[table_count];
            table_q     = new long[table_count];
            table_u     = new long[table_count];

            i = 0;
            for(int pN = 2; pN != 0; pN = sieve.getNextPrime(pN), i++) {
                prime_table[i] = (long)pN;
            }

            for(i = 0; i < table_count; i++) {
                table_q[i] =
                    (((order % new BigInteger(prime_table[i])).LongValue()) *
                    (long)2) % prime_table[i];
            }

            while(true) {
                u = new BigInteger();
                u.genRandomBits((int)primeBits, random);
                u.setBit(primeBits - 1);
                aux = order << 1;
                aux2 = u % aux;
                u = u - aux2;
                u = u + one;

                if(u.bitCount() <= (primeBits - 1))
                    continue;

                for(j = 0; j < table_count; j++) {
                    table_u[j] =
                        (u % new BigInteger(prime_table[j])).LongValue();
                }

                aux2 = order << 1;

                for(i = 0; i < (1 << 24); i++) {
                    long cur_p;
                    long value;

                    flag = true;
                    for(j = 1; j < table_count; j++) {
                        cur_p = prime_table[j];
                        value = table_u[j];
                        if(value >= cur_p)
                            value -= cur_p;
                        if(value == 0)
                            flag = false;
                        table_u[j] = value + table_q[j];
                    }
                    if(!flag)
                        continue;

                    aux   = aux2 * new BigInteger(i);
                    prime = u + aux;

                    if(prime.bitCount() > primeBits)
                        continue;

                    if(prime.isProbablePrime(20))
                        break;
                }

                if(i < (1 << 24))
                    break;
            }

            return new BigInteger[] { prime, order };
        }
Ejemplo n.º 51
0
            /// <summary>
            /// Adds padding to the input data and returns the padded data.
            /// </summary>
            /// <param name="dataBytes">Data to be padded prior to encryption</param>
            /// <param name="parameters">RSA Parameters used for padding computation</param>
            /// <returns>Padded message</returns>
            public byte[] EncodeMessage( byte[] dataBytes, RSAParameters parameters )
            {
                //Iterator
                int i = 0;

                //Get the size of the data to be encrypted
                m_mLen = dataBytes.Length;

                //Get the size of the public modulus (will serve as max length for cipher text)
                m_k = parameters.N.Length;

                if( m_mLen > GetMaxMessageLength( parameters ) ) {
                    throw new Exception( "Bad Data." );
                }

                //Generate the random octet seed (same length as hash)
                BigInteger biSeed = new BigInteger();
                biSeed.genRandomBits( m_hLen * 8, new Random() );
                byte[] bytSeed = biSeed.getBytesRaw();

                //Make sure all of the bytes are greater than 0.
                for( i = 0; i <= bytSeed.Length - 1; i++ ) {
                    if( bytSeed[i] == 0x00 ) {
                        //Replacing with the prime byte 17, no real reason...just picked at random.
                        bytSeed[i] = 0x17;
                    }
                }

                //Mask the seed with MFG Function(SHA1 Hash)
                //This is the mask to be XOR'd with the DataBlock below.
                byte[] dbMask = CryptoMathematics.OAEPMGF( bytSeed, m_k - m_hLen - 1, m_hLen, m_hashProvider );

                //Compute the length needed for PS (zero padding) and
                //fill a byte array to the computed length
                int psLen = GetMaxMessageLength( parameters ) - m_mLen;

                //Generate the SHA1 hash of an empty L (Label).  Label is not used for this
                //application of padding in the RSA specification.
                byte[] lHash = m_hashProvider.ComputeHash( System.Text.Encoding.UTF8.GetBytes( string.Empty.ToCharArray() ) );

                //Create a dataBlock which will later be masked.  The
                //data block includes the concatenated hash(L), PS,
                //a 0x01 byte, and the message.
                int dbLen = m_hLen + psLen + 1 + m_mLen;
                byte[] dataBlock = new byte[dbLen];

                int cPos = 0;
                //Current position

                //Add the L Hash to the data blcok
                for( i = 0; i <= lHash.Length - 1; i++ ) {
                    dataBlock[cPos] = lHash[i];
                    cPos += 1;
                }

                //Add the zero padding
                for( i = 0; i <= psLen - 1; i++ ) {
                    dataBlock[cPos] = 0x00;
                    cPos += 1;
                }

                //Add the 0x01 byte
                dataBlock[cPos] = 0x01;
                cPos += 1;

                //Add the message
                for( i = 0; i <= dataBytes.Length - 1; i++ ) {
                    dataBlock[cPos] = dataBytes[i];
                    cPos += 1;
                }

                //Create the masked data block.
                byte[] maskedDB = CryptoMathematics.BitwiseXOR( dbMask, dataBlock );

                //Create the seed mask
                byte[] seedMask = CryptoMathematics.OAEPMGF( maskedDB, m_hLen, m_hLen, m_hashProvider );

                //Create the masked seed
                byte[] maskedSeed = CryptoMathematics.BitwiseXOR( bytSeed, seedMask );

                //Create the resulting cipher - starting with a 0 byte.
                byte[] result = new byte[parameters.N.Length];
                result[0] = 0x00;

                //Add the masked seed
                maskedSeed.CopyTo( result, 1 );

                //Add the masked data block
                maskedDB.CopyTo( result, maskedSeed.Length + 1 );

                return result;
            }