Esempio n. 1
0
        /// <summary>
        /// Creates an ECDSA instance by recovering a public key given a hash, recovery ID, and r and s components of the resulting signature of the hash. Throws an exception if recovery is not possible.
        /// </summary>
        /// <param name="hash">The hash of the data which was signed.</param>
        /// <param name="recoveryId">The recovery ID of ECDSA during signing.</param>
        /// <param name="ecdsa_r">The r component of the ECDSA signature for the provided hash.</param>
        /// <param name="ecdsa_s">The s component of the ECDSA signature for the provided hash.</param>
        /// <returns>Returns the quotient/public key which was used to sign this hash.</returns>
        public static new EthereumEcdsaBouncyCastle Recover(Span <byte> hash, byte recoveryId, BigInteger ecdsa_r, BigInteger ecdsa_s)
        {
            // Source: http://www.secg.org/sec1-v2.pdf (Section 4.1.6 - Public Key Recovery Operation)

            // Recovery ID must be between 0 and 4 (0 and 1 is all that should be used, but we support multiple cases in case)
            if (recoveryId < 0 || recoveryId > 3)
            {
                throw new ArgumentException($"ECDSA public key recovery must have a v parameter between [0, 3]. Value provided is {recoveryId.ToString(CultureInfo.InvariantCulture)}");
            }

            // NOTES:
            // First bit of recoveryID being set means y is odd, otherwise it is even.
            // The second bit indicates which item of the two to choose.

            // If the hash is null, we'll assume it's a zero length byte array
            if (hash == null)
            {
                hash = Array.Empty <byte>();
            }

            // Obtain our elliptic curve parameters
            Org.BouncyCastle.Math.BigInteger r = ecdsa_r.ToBouncyCastleBigInteger();
            Org.BouncyCastle.Math.BigInteger s = ecdsa_s.ToBouncyCastleBigInteger();
            Org.BouncyCastle.Math.BigInteger j = Org.BouncyCastle.Math.BigInteger.ValueOf((long)recoveryId >> 1);
            Org.BouncyCastle.Math.BigInteger x = j.Multiply(Secp256k1Curve.Parameters.N).Add(r);

            // To obtain our curve point R, we decode it with an extra byte for Y descriptor which mentions if Y is even or odd.
            int curveLength = X9IntegerConverter.GetByteLength(Secp256k1Curve.Parameters.Curve);

            byte[] xdata = X9IntegerConverter.IntegerToBytes(x, curveLength + 1);
            xdata[0] = (byte)(0x2 | (recoveryId & 1));
            ECPoint r1 = Secp256k1Curve.Parameters.Curve.DecodePoint(xdata);

            // nR should be infinity.
            if (!r1.Multiply(Secp256k1Curve.Parameters.N).IsInfinity)
            {
                throw new ArgumentException("ECDSA's nR should be the point at infinity.");
            }

            // We obtain an integer representation of our hash.
            Org.BouncyCastle.Math.BigInteger e = new Org.BouncyCastle.Math.BigInteger(1, hash.ToArray());

            // Next we'll want the multiplicative inverse of r (~r)
            Org.BouncyCastle.Math.BigInteger rInverse = r.ModInverse(Secp256k1Curve.Parameters.N);

            // Next we get the additive inverse of our hash, subtracting it from zero, and bounding it accordingly.
            Org.BouncyCastle.Math.BigInteger eAddInverse = Org.BouncyCastle.Math.BigInteger.Zero.Subtract(e).Mod(Secp256k1Curve.Parameters.N);

            // Using the inverse of r we have, we can multiply it by s to get our ~r * s.
            Org.BouncyCastle.Math.BigInteger rsInverse = rInverse.Multiply(s).Mod(Secp256k1Curve.Parameters.N);

            // Using the inverse of r we have, and the inverse of e, we can have ~r * -e
            Org.BouncyCastle.Math.BigInteger reInverse = rInverse.Multiply(eAddInverse).Mod(Secp256k1Curve.Parameters.N);

            // Q = ((~r * s) * R) + ((~r * -e) * G) => (~r * sR) + (~r * -eG) => ~r (sR - eG)
            ECPoint q = ECAlgorithms.SumOfTwoMultiplies(Secp256k1Curve.Parameters.G, reInverse, r1, rsInverse).Normalize();

            // Obtain our public key from this
            return(new EthereumEcdsaBouncyCastle(Secp256k1Curve.Parameters.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(false), EthereumEcdsaKeyType.Public));
        }
Esempio n. 2
0
        /// <summary>
        /// Converts a base-58 string to a byte array, returning null if it wasn't valid.
        /// </summary>
        public static byte[] ToByteArray(string base58)
        {
            Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0");
            string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            foreach (char c in base58) {
                if (b58.IndexOf(c) != -1) {
                    bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58"));
                    bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString()));
                } else {
                    return null;
                }
            }

            byte[] bb = bi2.ToByteArrayUnsigned();

            // interpret leading '1's as leading zero bytes
            foreach (char c in base58) {
                if (c != '1') break;
                byte[] bbb = new byte[bb.Length + 1];
                Array.Copy(bb, 0, bbb, 1, bb.Length);
                bb = bbb;
            }

            return bb;
        }
Esempio n. 3
0
        /// <summary>
        /// Converts a base-58 string to a byte array, returning null if it wasn't valid.
        /// </summary>
        public static byte[] ToByteArray(string base58)
        {
            Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0");
            string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            foreach (char c in base58)
            {
                if (b58.IndexOf(c) != -1)
                {
                    bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58"));
                    bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString()));
                }
                else
                {
                    return(null);
                }
            }

            byte[] bb = bi2.ToByteArrayUnsigned();

            // interpret leading '1's as leading zero bytes
            foreach (char c in base58)
            {
                if (c != '1')
                {
                    break;
                }
                byte[] bbb = new byte[bb.Length + 1];
                Array.Copy(bb, 0, bbb, 1, bb.Length);
                bb = bbb;
            }

            return(bb);
        }
Esempio n. 4
0
        public RSA(int bits)
        {
            p = Helper.GenerateBigIntegerPrimes(bits);
            q = Helper.GenerateBigIntegerPrimes(bits);
            Console.WriteLine("p generated " + p);
            Console.WriteLine("q generated " + q);
            n = p.Multiply(q);
            Console.WriteLine("n = " + n);
            BigInteger p1 = p.Subtract(new BigInteger("1"));
            BigInteger q1 = q.Subtract(new BigInteger("1"));

            fn = p1.Multiply(q1);
            Console.WriteLine("Функция Эйлера = " + fn);
            int[]  er   = new[] { 17, 257, 65537 };
            Random rand = new Random((int)System.DateTime.Now.Ticks);

            e = new BigInteger(er[rand.Next(0, er.Length)].ToString());
            Console.WriteLine("e = " + e);

            d = e.ModInverse(fn);
            Console.WriteLine("d = " + d);

            Console.WriteLine("Public Key: " + e + ", " + n);
            Console.WriteLine("Private Key: " + d + ", " + n);
        }
        public static byte[] FromBase58String(string base58)
        {
            Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0");

            foreach (char c in base58)
            {
                if (b58.IndexOf(c) != -1)
                {
                    bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58"));
                    bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString()));
                }
                else
                {
                    return(null);
                }
            }

            byte[] bb = bi2.ToByteArrayUnsigned();

            // interpret leading '1's as leading zero bytes
            foreach (char c in base58)
            {
                if (c != leadingZeroCharacter[0])
                {
                    break;
                }

                byte[] bbb = new byte[bb.Length + 1];
                Array.Copy(bb, 0, bbb, 1, bb.Length);
                bb = bbb;
            }

            return(bb);
        }
        static void test()
        {
            RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator();

            rsaKeyPairGnr_s.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 32));
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair_s = rsaKeyPairGnr_s.GenerateKeyPair();

            RsaKeyParameters pubKey = (RsaKeyParameters)keyPair_s.Public;
            RsaKeyParameters prKey  = (RsaKeyParameters)keyPair_s.Private;

            IAsymmetricBlockCipher cipher = new RsaEngine();

            cipher.Init(true, prKey);
            byte[] plain_byte = BitConverter.GetBytes(10);

            byte[] enc = cipher.ProcessBlock(plain_byte, 0, plain_byte.Length);

            Org.BouncyCastle.Math.BigInteger test = new Org.BouncyCastle.Math.BigInteger(enc);
            Console.WriteLine(test);

            test = test.Multiply(new Org.BouncyCastle.Math.BigInteger(BitConverter.GetBytes(2)));

            test = test.Mod(prKey.Modulus);

            Console.WriteLine(test);

            byte[] new_enc = test.ToByteArray();

            cipher.Init(false, pubKey);

            byte[] dec = cipher.ProcessBlock(new_enc, 0, new_enc.Length);

            Console.WriteLine(BitConverter.ToInt32(dec));
        }
Esempio n. 7
0
        public static byte[] Base58ToByteArray(string base58)
        {
            Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0");
            string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            bool IgnoreChecksum = false;

            foreach (char c in base58)
            {
                if (b58.IndexOf(c) != -1)
                {
                    bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58"));
                    bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString()));
                }
                else if (c == '?')
                {
                    IgnoreChecksum = true;
                }
                else
                {
                    return null;
                }
            }

            byte[] bb = bi2.ToByteArrayUnsigned();

            // interpret leading '1's as leading zero bytes
            foreach (char c in base58)
            {
                if (c != '1') break;
                byte[] bbb = new byte[bb.Length + 1];
                Array.Copy(bb, 0, bbb, 1, bb.Length);
                bb = bbb;
            }

            if (bb.Length < 4) return null;

            if (IgnoreChecksum == false)
            {
                SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();
                byte[] checksum = sha256.ComputeHash(bb, 0, bb.Length - 4);
                checksum = sha256.ComputeHash(checksum);
                for (int i = 0; i < 4; i++)
                {
                    if (checksum[i] != bb[bb.Length - 4 + i]) return null;
                }
            }

            byte[] rv = new byte[bb.Length - 4];
            Array.Copy(bb, 0, rv, 0, bb.Length - 4);
            return rv;
        }
Esempio n. 8
0
        private byte[] Base58ToByteArray(string base58)
        {
            Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0");
            string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            bool IgnoreChecksum = false;

            foreach (char c in base58)
            {
                if (b58.IndexOf(c) != -1)
                {
                    bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58"));
                    bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString()));
                }
                else if (c == '?')
                {
                    IgnoreChecksum = true;
                }
                else
                {
                    return(null);
                }
            }

            byte[] bb = bi2.ToByteArrayUnsigned();

            // interpret leading '1's as leading zero bytes
            foreach (char c in base58)
            {
                if (c != '1')
                {
                    break;
                }
                byte[] bbb = new byte[bb.Length + 1];
                System.Array.Copy(bb, 0, bbb, 1, bb.Length);
                bb = bbb;
            }

            if (bb.Length < 4)
            {
                return(null);
            }

            if (IgnoreChecksum == false)
            {
                ////////////////////////////////////SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();
                SHA256 sha256 = SHA256.Create();
                // SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();
                byte[] checksum = sha256.ComputeHash(bb, 0, bb.Length - 4);
                checksum = sha256.ComputeHash(checksum);
                for (int i = 0; i < 4; i++)
                {
                    if (checksum[i] != bb[bb.Length - 4 + i])
                    {
                        return(null);
                    }
                }
            }

            byte[] rv = new byte[bb.Length - 4];
            System.Array.Copy(bb, 0, rv, 0, bb.Length - 4);
            return(rv);
        }
        static void Main(string[] args)
        {
            string server = "127.0.0.1";

            Int32         port   = 13000;
            TcpClient     client = new TcpClient(server, port);
            NetworkStream stream = client.GetStream();

            g = new Org.BouncyCastle.Math.BigInteger(2.ToString());
            p = new Org.BouncyCastle.Math.BigInteger(31.ToString());
            q = new Org.BouncyCastle.Math.BigInteger(5.ToString());
            int n = Int32.Parse(args[0]);

            gen_keys();

            Org.BouncyCastle.Math.BigInteger[] P = req_keys(n - 1);

            int[] V = gen_v(n - 1);



            //Start time
            DateTime now = DateTime.Now;

            Console.WriteLine("Strat Second: {0}", now.Millisecond);


            Random random = new Random();
            int    s      = 4;

            //int s = 29;
            Org.BouncyCastle.Math.BigInteger U = (g.Pow(s)).Mod(p);
            for (int i = 0; i < n - 1; ++i)
            {
                U = U.Multiply((P[i].Pow(V[i])).Mod(p)).Mod(p);
            }

            byte[] bytes;

            bytes = new byte[204800];
            bytes = Encoding.UTF8.GetBytes(U.ToString());
            stream.Write(bytes);

            stream.Flush();

            bytes = new byte[64];
            stream.Read(bytes, 0, bytes.Length);

            int c = Int32.Parse(Encoding.UTF8.GetString(bytes));


            int v_p = c;

            for (int i = 0; i < n - 1; ++i)
            {
                v_p = v_p ^ V[i];
            }


            string V_str = v_p + "|";

            for (int i = 0; i < n - 1; ++i)
            {
                V_str += V[i] + "|";
            }

            string P_str = A_p.ToString() + "|";

            for (int i = 0; i < n - 1; ++i)
            {
                P_str += P[i] + "|";
            }

            Org.BouncyCastle.Math.BigInteger a_p_big = new Org.BouncyCastle.Math.BigInteger(a_p.ToString());
            Org.BouncyCastle.Math.BigInteger v_p_big = new Org.BouncyCastle.Math.BigInteger(v_p.ToString());

            Org.BouncyCastle.Math.BigInteger s_big = new Org.BouncyCastle.Math.BigInteger(s.ToString());

            Org.BouncyCastle.Math.BigInteger r_big = (s_big.Add((a_p_big.Multiply(v_p_big)).Negate())).Mod(q);
            //int r = (s - ((a_p * v_p) % 31));
            //int r = Int32.Parse(r_big.ToString());

            string r_str = r_big.ToString();

            string msg = V_str + P_str + r_str;

            bytes = new byte[204800];
            bytes = Encoding.UTF8.GetBytes(msg);
            stream.Write(bytes);

            stream.Flush();
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            int n = Int32.Parse(args[0]);

            g = new Org.BouncyCastle.Math.BigInteger(2.ToString());
            p = new Org.BouncyCastle.Math.BigInteger(31.ToString());
            q = new Org.BouncyCastle.Math.BigInteger(5.ToString());

            TcpListener server    = null;
            Int32       port      = 13000;
            IPAddress   localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data


            TcpClient     client = server.AcceptTcpClient();
            NetworkStream stream = client.GetStream();

            byte[] bytes;

            bytes = new byte[204800];
            stream.Read(bytes, 0, bytes.Length);

            string U = Encoding.UTF8.GetString(bytes);


            Random random = new Random();
            int    c      = random.Next(1, 4);

            bytes = new byte[64];
            bytes = Encoding.UTF8.GetBytes(c.ToString());
            stream.Write(bytes);

            stream.Flush();


            bytes = new byte[204800];
            stream.Read(bytes, 0, bytes.Length);

            string msg = Encoding.UTF8.GetString(bytes);

            string[] temp_split = msg.Split("|");

            int[] V  = new int[n];
            int   c0 = 0;

            for (int i = 0; i < n; ++i)
            {
                V[i] = Int32.Parse(temp_split[i]);
                c0   = c0 ^ V[i];
            }


            Org.BouncyCastle.Math.BigInteger[] P = new Org.BouncyCastle.Math.BigInteger[n];
            for (int i = 0; i < n; ++i)
            {
                P[i] = new Org.BouncyCastle.Math.BigInteger(temp_split[n + i]);
            }

            int r = Int32.Parse(temp_split[2 * n]);

            if (c0 == c)
            {
                Console.WriteLine("1st verification PASS");
            }
            else
            {
                Console.WriteLine("1st verification FAIL");
            }

            Org.BouncyCastle.Math.BigInteger U0 = (g.Pow(r)).Mod(p);
            for (int i = 0; i < n; ++i)
            {
                U0 = U0.Multiply((P[i].Pow(V[i])).Mod(p)).Mod(p);
            }
            Console.WriteLine(U);
            Console.WriteLine(U0);

            string U1   = U0.ToString();
            bool   flag = true;

            for (int i = 0; i < U1.Length; ++i)
            {
                if (U1[i] != U[i])
                {
                    Console.WriteLine("2nd verification FAIL");
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                Console.WriteLine("2nd verification PASS");
            }
            //End time

            DateTime now = DateTime.Now;

            Console.WriteLine("Strat Second: {0}", now.Millisecond);
        }