Exemplo n.º 1
0
        /// <summary>
        /// To the bouncy castle big integer.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static Org.BouncyCastle.Math.BigInteger ToBouncyBigInteger(this BigInteger value)
        {
            var bytes  = Utility.GetBytes(value);
            var bigint = new Org.BouncyCastle.Math.BigInteger(bytes);

            return(bigint);
        }
Exemplo n.º 2
0
 public void DecodeWifTest()
 {
     //https://en.bitcoin.it/wiki/Wallet_import_format
     Org.BouncyCastle.Math.BigInteger actual = BitcoinHelper.DecodeWif("5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ");
     //Assert.IsTrue(actual.ToString() == "0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D");
     Assert.IsTrue(actual.ToString() == "5500171714335001507730457227127633683517613019341760098818554179534751705629");
 }
Exemplo n.º 3
0
        private string ByteArrayToBase58(byte[] ba)
        {
            Org.BouncyCastle.Math.BigInteger addrremain = new Org.BouncyCastle.Math.BigInteger(1, ba);

            Org.BouncyCastle.Math.BigInteger big0  = new Org.BouncyCastle.Math.BigInteger("0");
            Org.BouncyCastle.Math.BigInteger big58 = new Org.BouncyCastle.Math.BigInteger("58");

            string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            string rv = "";

            while (addrremain.CompareTo(big0) > 0)
            {
                int d = System.Convert.ToInt32(addrremain.Mod(big58).ToString());
                addrremain = addrremain.Divide(big58);
                rv         = b58.Substring(d, 1) + rv;
            }

            // handle leading zeroes
            foreach (byte b in ba)
            {
                if (b != 0)
                {
                    break;
                }
                rv = "1" + rv;
            }
            return(rv);
        }
Exemplo n.º 4
0
        public AuthenticationHeaderValue GetLiveSessionHeaders(string token, string url, string verificationCode)
        {
            DiffieBytes ??= File.ReadAllBytes(@"dhparam.pem");
            Prime ??= new Org.BouncyCastle.Math.BigInteger(1, DiffieBytes);
            var g  = new Org.BouncyCastle.Math.BigInteger("2", 10);
            var dh = new DHParameters(Prime, g);

            //var dhPrivateKeyParameters = keyPair.Private as DHPrivateKeyParameters;
            var challenge = dh.G.ModPow(DhRandom, dh.P);
            var diffie_hellman_challenge = BitConverter.ToString(challenge.ToByteArray()).Replace("-", "").ToLower();
            var nonce     = ClientHelpers.GetNonce();
            var timestamp = ClientHelpers.GetTimestamp();
            var data      = new Dictionary <string, string>
            {
                { "diffie_hellman_challenge", diffie_hellman_challenge },
                { "oauth_consumer_key", s_clientId },
                { "oauth_timestamp", timestamp.ToString() },
                { "oauth_nonce", nonce },
                { "oauth_signature_method", "RSA-SHA256" },
                { "oauth_token", token },
            };


            data.Add("oauth_signature", ClientHelpers.GetSignatureBaseString(_httpClient.BaseAddress.AbsoluteUri + url, data, verificationCode));
            return(ClientHelpers.GetDefaultAuthHeader(data, false));
        }
Exemplo n.º 5
0
        public static bool ValidateSignature(Hash data, ECSignature signature, ECKeyPair keyPair)
        {
#if NATIVE_ECDSA
            using (var ecdsa = ECDsa.Create(keyPair))
            {
                return(ecdsa.VerifyHash(data, signature.Signature));
            }
#else
            var derSignature = new DerSequence(
                new DerInteger(new Org.BouncyCastle.Math.BigInteger(1, signature.Signature.Take(32).ToArray())),
                new DerInteger(new Org.BouncyCastle.Math.BigInteger(1, signature.Signature.Skip(32).ToArray())))
                               .GetDerEncoded();

            ISigner            signer                   = SignerUtilities.GetSigner("NONEwithECDSA");
            X9ECParameters     curve                    = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName(keyPair.CurveType.ToString().ToLower());
            ECDomainParameters domain                   = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            Org.BouncyCastle.Math.BigInteger bn         = new Org.BouncyCastle.Math.BigInteger(keyPair.D);
            ECPrivateKeyParameters           parameters = new ECPrivateKeyParameters(bn, domain);
            FpCurve c         = (FpCurve)curve.Curve;
            var     publicKey = new FpPoint(c, new FpFieldElement(c.Q, new Org.BouncyCastle.Math.BigInteger(+1, keyPair.PublicKey.X)),
                                            new FpFieldElement(c.Q, new Org.BouncyCastle.Math.BigInteger(+1, keyPair.PublicKey.Y)));
            ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(publicKey, domain);
            signer.Init(false, publicKeyParameters);
            signer.BlockUpdate(data, 0, data.Length);
            bool ok = signer.VerifySignature(derSignature);
            return(ok);
#endif
        }
        private void btnCreateRecepients_Click(object sender, RoutedEventArgs e)
        {
            RSA RSA_Encryptor = new RSA();

            Org.BouncyCastle.Math.BigInteger secretPrimeNumber = PrimeNumberGenerator.genpr2(128, DateTime.Now.ToBinary());
            Dictionary <string, UserData>    tempDictionary    = new Dictionary <string, UserData>();
            UserData tempUserData;

            foreach (KeyValuePair <string, UserData> u in dataForEnc.UsersCollection)
            {
                u.Value.PlainSesKey = secretPrimeNumber.ToByteArray();

                tempUserData = RSA_Encryptor.EncryptSessionKey(u.Value);
                tempDictionary.Add(u.Key, tempUserData);


                // zapis kluczy do plików i szyfrowanie klucz sesyjnego
                RSA_Encryptor.writeRSAParametersToFile(tempUserData.PrivKey,
                                                       RSA_Configuration.keyDirectory + "\\private\\" + u.Key + "_priv.key", tempUserData.PasswdHash);
                RSA_Encryptor.writeRSAParametersToFile(tempUserData.PubKey,
                                                       RSA_Configuration.keyDirectory + "\\public\\" + u.Key + "_pub.key");
            }

            dataForEnc.UsersCollection = tempDictionary;
        }
Exemplo n.º 7
0
        private RsaKeyParameters MakeKey(String modulusHexString, String exponentHexString, bool isPrivateKey)
        {
            var modulus  = new Org.BouncyCastle.Math.BigInteger(modulusHexString, 16);
            var exponent = new Org.BouncyCastle.Math.BigInteger(exponentHexString, 16);

            return(new RsaKeyParameters(isPrivateKey, modulus, exponent));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Calculates an ECDSA signature in DER format for the given input hash. Note that the input is expected to be
        /// 32 bytes long.
        /// </summary>
        public byte[] Sign(byte[] input, Org.BouncyCastle.Math.BigInteger privateKey)
        {
            const string BITCOIN_CURVE = "secp256k1";
            ECDsaSigner  signer        = new ECDsaSigner();

            Org.BouncyCastle.Asn1.X9.X9ECParameters ecp = SecNamedCurves.GetByName(BITCOIN_CURVE);
            ECDomainParameters EcParameters             = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H);

            var privateKeyParameters = new ECPrivateKeyParameters(privateKey, EcParameters);

            signer.Init(true, privateKeyParameters);
            var signatures = signer.GenerateSignature(input);

            // What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream
            // of the type used by BitCoin we have to encode them using DER encoding, which is just a way to pack the two
            // components into a structure.
            using (var byteOutputStream = new MemoryStream())
            {
                var derSequenceGenerator = new DerSequenceGenerator(byteOutputStream);
                derSequenceGenerator.AddObject(new DerInteger(signatures[0]));
                derSequenceGenerator.AddObject(new DerInteger(signatures[1]));
                derSequenceGenerator.Close();
                return(byteOutputStream.ToArray());
            }
        }
Exemplo n.º 9
0
        public static string FromByteArray(byte[] ba)
        {
            Org.BouncyCastle.Math.BigInteger addrremain = new Org.BouncyCastle.Math.BigInteger(1, ba);

            Org.BouncyCastle.Math.BigInteger big0 = new Org.BouncyCastle.Math.BigInteger("0");
            Org.BouncyCastle.Math.BigInteger big58 = new Org.BouncyCastle.Math.BigInteger("58");

            string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            string rv = "";

            while (addrremain.CompareTo(big0) > 0) {
                int d = Convert.ToInt32(addrremain.Mod(big58).ToString());
                addrremain = addrremain.Divide(big58);
                rv = b58.Substring(d, 1) + rv;
            }

            // handle leading zeroes
            foreach (byte b in ba) {
                if (b != 0) break;
                rv = "1" + rv;

            }
            return rv;
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
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;
        }
        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);
        }
        public static string ToBase58String(byte[] data)
        {
            Org.BouncyCastle.Math.BigInteger toConvertToBase58 = new Org.BouncyCastle.Math.BigInteger(1, data);

            Org.BouncyCastle.Math.BigInteger big0  = new Org.BouncyCastle.Math.BigInteger("0");
            Org.BouncyCastle.Math.BigInteger big58 = new Org.BouncyCastle.Math.BigInteger("58");

            StringBuilder base58Builder = new StringBuilder();

            while (toConvertToBase58.CompareTo(big0) > 0)
            {
                int d = Convert.ToInt32(toConvertToBase58.Mod(big58).ToString());
                toConvertToBase58 = toConvertToBase58.Divide(big58);

                base58Builder.Insert(0, b58.Substring(d, 1));
            }

            // handle leading zeroes
            foreach (byte b in data)
            {
                if (b != 0)
                {
                    break;
                }

                base58Builder.Insert(0, leadingZeroCharacter);
            }

            return(base58Builder.ToString());
        }
Exemplo n.º 14
0
        /// <summary>
        ///     Create a BouncyCastle AsymmetricCipherKeyPair and associated
        ///     X509Certificate
        ///     <remarks>
        ///         Based on:
        ///         http://stackoverflow.com/questions/3770233/is-it-possible-to-programmatically-generate-an-x509-certificate-using-only-c
        ///         http://web.archive.org/web/20100504192226/http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx
        ///         requires http://www.bouncycastle.org/csharp/
        ///     </remarks>
        ///     <param name="subjectName">
        ///         value assigned to CN field of the X.500 Distinguished Name
        ///         assigned to the certificate.
        ///         <remarks>
        ///             see http://msdn.microsoft.com/en-us/library/windows/desktop/aa366101(v=vs.85).aspx
        ///             for Distinguished Name format
        ///             See http://stackoverflow.com/questions/5136198/what-strings-are-allowed-in-the-common-name-attribute-in-an-x-509-certificate
        ///             answer 2 for encoding details
        ///             Input is appended to "CN=".
        ///         </remarks>
        ///     </param>
        ///     <remarks>
        ///         Default is EmailProtection
        ///     </remarks>
        /// </summary>
        public static (X509Certificate Certificate, AsymmetricCipherKeyPair KeyPair) GenerateSelfSignedCertificate(string subjectName)
        {
            var kpGenerator = new RsaKeyPairGenerator();

            // certificate strength 2048 bits
            kpGenerator.Init(new KeyGenerationParameters(
                                 new SecureRandom(new CryptoApiRandomGenerator()), 2048));

            var kp = kpGenerator.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var certName = new X509Name("CN=" + subjectName);
            var serialNo = BigInteger.ProbablePrime(120, new Random());

            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);
            gen.SetNotAfter(DateTime.Now.AddYears(30));
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetPublicKey(kp.Public);

            gen.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id,
                false,
                new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public),
                    new GeneralNames(new GeneralName(certName)),
                    serialNo));

            return(gen.Generate(new Asn1SignatureFactory("SHA256withRSA", kp.Private)), kp);
        }
Exemplo n.º 15
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);
        }
Exemplo n.º 16
0
        public EthereumEcdsaBouncyCastle(Memory <byte> key, EthereumEcdsaKeyType keyType)
        {
            // Set the key type
            KeyType = keyType;

            // Instantiate our key depending on what type of key it is.
            if (KeyType == EthereumEcdsaKeyType.Public)
            {
                // If it's only 64 bytes, we need to add our prefix. (Source: https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm)
                if (key.Length == PUBLIC_KEY_SIZE)
                {
                    key = new byte[] { 0x4 }.Concat(key.ToArray());
                }

                // Obtain our public key parameters by using the provided quotient.
                ECPoint q = Secp256k1Curve.Parameters.Curve.DecodePoint(key.ToArray());
                PublicKey = new ECPublicKeyParameters(ALGORITHM, q, Secp256k1Curve.DomainParameters);
            }
            else
            {
                // Obtain our private key parameters
                Org.BouncyCastle.Math.BigInteger keyInt = new Org.BouncyCastle.Math.BigInteger(1, key.ToArray());
                PrivateKey = new ECPrivateKeyParameters(ALGORITHM, keyInt, Secp256k1Curve.DomainParameters);

                // Obtain Q from our private key.
                ECPoint q = Secp256k1Curve.Parameters.G.Multiply(PrivateKey.D);
                PublicKey = new ECPublicKeyParameters(ALGORITHM, q, Secp256k1Curve.DomainParameters);
            }
        }
Exemplo n.º 17
0
        /*
         * // https://csharp.hotexamples.com/examples/Org.BouncyCastle.Crypto.Parameters/ECPrivateKeyParameters/-/php-ecprivatekeyparameters-class-examples.html
         * public ECDiffieHellmanBc(Int32 keySize)
         * {
         *  Org.BouncyCastle.Asn1.X9.X9ECParameters ecParams;
         *  switch (keySize) {
         *  case 256:
         *      ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256r1");
         *      break;
         *  case 384:
         *      ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp384r1");
         *      break;
         *  case 521:
         *      ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp521r1");
         *      break;
         *  default:
         */


        // https://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml
        // https://tools.ietf.org/html/rfc5933
        private static PublicKey toECGOSTPublicKey(byte[] keyBytes, ECKeyInfo keyinfo) // throws IOException, GeneralSecurityException
        {
            DNSInput @in = new DNSInput(keyBytes);

            Org.BouncyCastle.Math.BigInteger x = Helpers.readBigIntegerLittleEndian(@in, keyinfo.length);
            Org.BouncyCastle.Math.BigInteger y = Helpers.readBigIntegerLittleEndian(@in, keyinfo.length);

            // OID to be found in Org.BouncyCastle.Security.GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");
            // Org.BouncyCastle.Crypto.Parameters.ECDomainParameters domain = Org.BouncyCastle.Asn1.CryptoPro.ECGost3410NamedCurves.GetByOid(Org.BouncyCastle.Asn1.CryptoPro.CryptoProObjectIdentifiers.GostR3410x94CryptoProA);
            // Org.BouncyCastle.Math.EC.ECCurve c = domain.Curve;
            // Org.BouncyCastle.Math.EC.ECPoint q = new Org.BouncyCastle.Math.EC.FpPoint(c, c.FromBigInteger(x), c.FromBigInteger(y));

            // Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters publicParams = new Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters(q, domain);



            Org.BouncyCastle.Math.EC.ECPoint q = keyinfo.curve.CreatePoint(x, y);
            Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters publicParams = new Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters(q, keyinfo.spec);


            // Org.BouncyCastle.Crypto.Signers.ECGost3410Signer

            // Org.BouncyCastle.Security.PublicKeyFactory.CreateKey(new Org.BouncyCastle.Asn1.X509.SubjectPublicKeyInfo())

            /*
             * ECPoint q = new ECPoint(x, y);
             *
             * KeyFactory factory = KeyFactory.getInstance("ECGOST3410");
             * return factory.generatePublic(new ECPublicKeySpec(q, keyinfo.spec));
             */

            return(PublicKey.CreateInstance(publicParams));
        }
Exemplo n.º 18
0
        public static byte[] fromDSAPublicKey(DSAPublicKey key)
        {
            DNSOutput @out = new DNSOutput();

            Org.BouncyCastle.Crypto.Parameters.DsaPublicKeyParameters dp = key.PublicKey;


            // BigInteger q = key.getParams().getQ();
            Org.BouncyCastle.Math.BigInteger q = dp.Parameters.Q;
            // BigInteger p = key.getParams().getP();
            Org.BouncyCastle.Math.BigInteger p = dp.Parameters.P;
            // BigInteger g = key.getParams().getG();
            Org.BouncyCastle.Math.BigInteger g = dp.Parameters.G;
            // BigInteger y = key.getY();
            Org.BouncyCastle.Math.BigInteger y = dp.Y;


            int t = (p.ToByteArray().Length - 64) / 8;

            @out.writeU8(t);

            Helpers.writeBigInteger(@out, q);
            Helpers.writeBigInteger(@out, p);
            Helpers.writePaddedBigInteger(@out, g, 8 * t + 64);
            Helpers.writePaddedBigInteger(@out, y, 8 * t + 64);

            return(@out.toByteArray());
        }
Exemplo n.º 19
0
        private static PublicKey toDSAPublicKey(byte[] keyBytes) // throws IOException, GeneralSecurityException, MalformedKeyException
        {
            DNSInput @in = new DNSInput(keyBytes);

            int t = @in.readU8();

            if (t > 8)
            {
                throw new MalformedKeyException(keyBytes, ARSoft.Tools.Net.Dns.DnsSecAlgorithm.Dsa);
            }

            Org.BouncyCastle.Math.BigInteger q = Helpers.readBigInteger(@in, 20);
            Org.BouncyCastle.Math.BigInteger p = Helpers.readBigInteger(@in, 64 + t * 8);
            Org.BouncyCastle.Math.BigInteger g = Helpers.readBigInteger(@in, 64 + t * 8);
            Org.BouncyCastle.Math.BigInteger y = Helpers.readBigInteger(@in, 64 + t * 8);

            /*
             * KeyFactory factory = KeyFactory.getInstance("DSA");
             * return factory.generatePublic(new DSAPublicKeySpec(y, p, q, g));
             */

            Org.BouncyCastle.Crypto.Parameters.DsaParameters para = new Org.BouncyCastle.Crypto.Parameters.DsaParameters(p, q, g);

            Org.BouncyCastle.Crypto.Parameters.DsaPublicKeyParameters dp = new Org.BouncyCastle.Crypto.Parameters.DsaPublicKeyParameters(y, para);

            return(PublicKey.CreateInstance(dp));
        }
Exemplo n.º 20
0
        public ECKeyInfo(
            int length,
            string p_str,
            string a_str,
            string b_str,
            string gx_str,
            string gy_str,
            string n_str)
        {
            this.length = length;
            p           = new Org.BouncyCastle.Math.BigInteger(p_str, 16);
            a           = new Org.BouncyCastle.Math.BigInteger(a_str, 16);
            b           = new Org.BouncyCastle.Math.BigInteger(b_str, 16);
            gx          = new Org.BouncyCastle.Math.BigInteger(gx_str, 16);
            gy          = new Org.BouncyCastle.Math.BigInteger(gy_str, 16);
            n           = new Org.BouncyCastle.Math.BigInteger(n_str, 16);
            Org.BouncyCastle.Math.BigInteger h = Org.BouncyCastle.Math.BigInteger.One;

            this.curve = new Org.BouncyCastle.Math.EC.FpCurve(p, a, b, n, h);

            //spec = new ECParameterSpec(curve, new ECPoint(gx, gy), n, 1);
            this.spec = new Org.BouncyCastle.Crypto.Parameters.ECDomainParameters(
                curve
                , curve.CreatePoint(gx, gy) // G
                , n
                , h
                );
        }
Exemplo n.º 21
0
        private static byte[] fromRSAPublicKey(RSAPublicKey key)
        {
            DNSOutput @out = new DNSOutput();

            Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters kp = key.PublicKey;

            // BigInteger exponent = key.getPublicExponent();
            Org.BouncyCastle.Math.BigInteger exponent = kp.Exponent;

            // BigInteger modulus = key.getModulus();
            Org.BouncyCastle.Math.BigInteger modulus = kp.Modulus;


            int exponentLength = Helpers.BigIntegerLength(exponent);

            if (exponentLength < 256)
            {
                @out.writeU8(exponentLength);
            }
            else
            {
                @out.writeU8(0);
                @out.writeU16(exponentLength);
            }

            Helpers.writeBigInteger(@out, exponent);
            Helpers.writeBigInteger(@out, modulus);

            return(@out.toByteArray());
        }
Exemplo n.º 22
0
 private static byte[] BigIntToFixexLengthBytes(Org.BouncyCastle.Math.BigInteger rOrS)
 {
     // for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
     // r and s are the result of mod n, so they should be less than n and have length<=32
     byte[] rs = rOrS.ToByteArray();
     if (rs.Length == RS_LEN)
     {
         return(rs);
     }
     else if (rs.Length == RS_LEN + 1 && rs[0] == 0)
     {
         return(Org.BouncyCastle.Utilities.Arrays.CopyOfRange(rs, 1, RS_LEN + 1));
     }
     else if (rs.Length < RS_LEN)
     {
         byte[] result = new byte[RS_LEN];
         Org.BouncyCastle.Utilities.Arrays.Fill(result, (byte)0);
         Buffer.BlockCopy(rs, 0, result, RS_LEN - rs.Length, rs.Length);
         return(result);
     }
     else
     {
         throw new ArgumentException("err rs: " + Org.BouncyCastle.Utilities.Encoders.Hex.ToHexString(rs));
     }
 }
Exemplo n.º 23
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));
        }
Exemplo n.º 24
0
        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));
        }
Exemplo n.º 25
0
        public static byte[] GeneratePublicKey(byte[] privateKey)
        {
            Org.BouncyCastle.Math.BigInteger privateKeyInt = new Org.BouncyCastle.Math.BigInteger(+1, privateKey);

            var parameters = SecNamedCurves.GetByName("secp256k1");

            Org.BouncyCastle.Math.EC.ECPoint point = parameters.G.Multiply(privateKeyInt);

            byte[] pubKeyX = point.X.ToBigInteger().ToByteArrayUnsigned();
            byte[] pubKeyY = point.Y.ToBigInteger().ToByteArrayUnsigned();

            Console.WriteLine("Your X point on the Elliptic Curve is: " + Encoding.Unicode.GetString(pubKeyX));
            Console.WriteLine("Your Y point on the Elliptic Curve is: " + Encoding.Unicode.GetString(pubKeyY));

            byte[] pubKey = new byte[pubKeyX.Length + 1];

            // Copy pub key X over to pubKey
            pubKeyX.CopyTo(pubKey, 1);

            // Setup the parity byte
            if (point.Y.ToBigInteger().Mod(new Org.BouncyCastle.Math.BigInteger("2")) == new Org.BouncyCastle.Math.BigInteger("1"))
            {
                pubKey[0] = 0x03;
            }
            else
            {
                pubKey[0] = 0x02;
            }

            // Return the public key
            //return Tuple.Create(pubKeyX, pubKeyY);
            return(pubKey);
        }
Exemplo n.º 26
0
        public static string GetPublicKey(string privateKey)
        {
            var hexPrivateKey = ReferenceLib.ValidateAndGetHexPrivateKey(privateKey, 0x00);

            if (hexPrivateKey == null)
            {
                throw new Exception("error");
            }

            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");

            Org.BouncyCastle.Math.BigInteger Db = new Org.BouncyCastle.Math.BigInteger(hexPrivateKey);
            ECPoint dd = ps.G.Multiply(Db);

            byte[] pubaddr = new byte[65];
            byte[] Y       = dd.Y.ToBigInteger().ToByteArray();
            Array.Copy(Y, 0, pubaddr, 64 - Y.Length + 1, Y.Length);
            byte[] X = dd.X.ToBigInteger().ToByteArray();
            Array.Copy(X, 0, pubaddr, 32 - X.Length + 1, X.Length);
            pubaddr[0] = 4;

            var publicKey = ByteArrayToString(pubaddr);

            return(publicKey);
        }
Exemplo n.º 27
0
        public void WriteBigInteger(Org.BouncyCastle.Math.BigInteger big)
        {
            var data = big.ToByteArray();

            WriteInt(data.Length);
            writer.Write(data, 0, data.Length);
        }
Exemplo n.º 28
0
 /// <summary>
 /// Our default static constructor, sets static read only variables.
 /// </summary>
 static Secp256k1Curve()
 {
     Parameters       = Org.BouncyCastle.Crypto.EC.CustomNamedCurves.GetByName("secp256k1");
     DomainParameters = new ECDomainParameters(Parameters.Curve, Parameters.G, Parameters.N, Parameters.H);
     N        = Parameters.N.ToNumericsBigInteger();
     _b_halfN = Parameters.N.Divide(Org.BouncyCastle.Math.BigInteger.Two);
     _halfN   = _b_halfN.ToNumericsBigInteger();
 }
        static void gen_keys()
        {
            Random random = new Random();

            a_p = 2;

            A_p = g.Pow(a_p).Mod(q);
        }
Exemplo n.º 30
0
 public static byte[] ToByteArray(Org.BouncyCastle.Math.BigInteger bigint, int expectedLength)
 {
     byte[] data = bigint.ToByteArray();
     if (data.Length == expectedLength + 1)
     {
         return(data.Skip(1).Take(expectedLength).ToArray());
     }
     return(data);
 }
        public Org.BouncyCastle.Math.BigInteger readBCBigInteger()
        {
            var size = ReadInt();

            var i = new Org.BouncyCastle.Math.BigInteger(data, offset + totalSize, size);

            totalSize += size;
            return(i);
        }
Exemplo n.º 32
0
        public static byte[] getPublicKeyByteArray(byte[] privateKey)
        {
            Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math.BigInteger(1, privateKey);
            Org.BouncyCastle.Math.EC.ECPoint q = domain.G.Multiply(d);

            var publicParams = new ECPublicKeyParameters(q, domain);

            return(publicParams.Q.GetEncoded(true));
        }
Exemplo n.º 33
0
        private void InitializeRSA()
        {
            string[] keyComponents = publicKey.Split('|');
            var modulus = new Org.BouncyCastle.Math.BigInteger(keyComponents[1].ToLower(), 16);
            var exponent = new Org.BouncyCastle.Math.BigInteger(keyComponents[0].ToLower(), 16);
            RsaKeyParameters keyParams = new RsaKeyParameters(false, modulus, exponent);

            rsaCipher = CipherUtilities.GetCipher("RSA/None/PKCS1Padding");
            rsaCipher.Init(true, keyParams);
        }
Exemplo n.º 34
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;
        }
 public static ECPoint PrivKeyToPubKey(byte[] PrivKey)
 {
     if (PrivKey == null || PrivKey.Length > 32) throw new ApplicationException("Invalid private hex key");
     Org.BouncyCastle.Math.BigInteger Db = new Org.BouncyCastle.Math.BigInteger(1, PrivKey);
     var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
     return ps.G.Multiply(Db);
 }
 public static ECPoint PrivHexToPubKey(string PrivHex)
 {
     byte[] hex = ValidateAndGetHexPrivateKey(0x00, PrivHex, 33);
     if (hex == null) throw new ApplicationException("Invalid private hex key");
     Org.BouncyCastle.Math.BigInteger Db = new Org.BouncyCastle.Math.BigInteger(1, hex);
     var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
     return ps.G.Multiply(Db);
 }
        public static string PrivHexToPubHex(string PrivHex, ECPoint point)
        {
            byte[] hex = ValidateAndGetHexPrivateKey(0x00, PrivHex, 33);
            if (hex == null) throw new ApplicationException("Invalid private hex key");
            Org.BouncyCastle.Math.BigInteger Db = new Org.BouncyCastle.Math.BigInteger(hex);
            ECPoint dd = point.Multiply(Db);

            byte[] pubaddr = PubKeyToByteArray(dd);

            return ByteArrayToString(pubaddr);
        }
Exemplo n.º 38
0
        public bool VerifySignature(ImmutableArray<byte> scriptPubKey, Transaction tx, byte[] sig, byte[] pubKey, int inputIndex, out byte hashType, out byte[] txSignature, out byte[] txSignatureHash, out BigIntegerBouncy x, out BigIntegerBouncy y, out BigIntegerBouncy r, out BigIntegerBouncy s)
        {
            // get the 1-byte hashType off the end of sig
            hashType = sig[sig.Length - 1];

            // get the DER encoded portion of sig, which is everything except the last byte (the last byte being hashType)
            var sigDER = sig.Take(sig.Length - 1).ToArray();

            // get the simplified/signing version of the transaction
            txSignature = TxSignature(scriptPubKey, tx, inputIndex, hashType);

            // get the hash of the simplified/signing version of the transaction
            txSignatureHash = Crypto.DoubleSHA256(txSignature);

            // load pubKey
            ReadPubKey(pubKey, out x, out y);
            var publicKeyPoint = curve.Curve.CreatePoint(x, y, withCompression: false);
            var publicKeyParameters = new ECPublicKeyParameters(publicKeyPoint, domainParameters);

            // load sig
            ReadSigKey(sigDER, out r, out s);

            // init signer
            var signer = new ECDsaSigner();
            signer.Init(forSigning: false, parameters: publicKeyParameters);

            // verify that sig is a valid signature from pubKey for the simplified/signing transaction's hash
            var txSignatureHash2 = txSignatureHash;
            var r2 = r;
            var s2 = s;
            //TODO
            var result = BypassVerifySignature || new MethodTimer(false).Time("ECDsa Verify", () => signer.VerifySignature(txSignatureHash2.ToArray(), r2, s2));

            return result;
        }
Exemplo n.º 39
0
        private void ReadPubKey(byte[] pubKey, out BigIntegerBouncy x, out BigIntegerBouncy y)
        {
            // public key is encoded as 0x04<x><y>
            // where <x> and <y> are 32-byte unsigned, positive, big-endian integers
            // for a total length of 65 bytes

            if (pubKey.Length != 65 || pubKey[0] != 0x04)
                throw new Exception("TODO wrong public key type");

            x = new BigIntegerBouncy(1, pubKey.ToArray(), 1, 32);
            y = new BigIntegerBouncy(1, pubKey.ToArray(), 33, 32);
        }
Exemplo n.º 40
0
        private void ReadSigKey(byte[] sig, out BigIntegerBouncy r, out BigIntegerBouncy s)
        {
            // sig is two DER encoded integers: r and s
            // total length is variable

            using (var stream = new Asn1InputStream(sig.ToArray()))
            {
                var sequence = (DerSequence)stream.ReadObject();
                r = ((DerInteger)sequence[0]).Value;
                s = ((DerInteger)sequence[1]).Value;

                Debug.Assert(sequence.Count == 2);
                //TODO Debug.Assert(sig.SequenceEqual(sequence.GetDerEncoded()));
            }
        }
Exemplo n.º 41
0
        /// <summary>
        /// Check is the key is valid see RFC 2631, Section 2.1.5, http://www.ietf.org/rfc/rfc2631.txt
        /// </summary>
        public static bool IsValidPublicKey(Org.BouncyCastle.Math.BigInteger y, Org.BouncyCastle.Math.BigInteger p, Org.BouncyCastle.Math.BigInteger q)
        {
            Org.BouncyCastle.Math.BigInteger bn;

            // y must lie in [2,p-1]
            // check y < 2 then failed
            bn = new Org.BouncyCastle.Math.BigInteger("2");
            if (y.CompareTo(bn) < 0)
            {
                LibRTMPLogger.Log(LibRTMPLogLevel.Warning, "[CDR.LibRTMP.RTMPHelper.IsValidPublicKey] DH public key must be at least 2");
                return false;
            }

            // y must lie in [2,p-1]
            bn = new Org.BouncyCastle.Math.BigInteger(p.ToString());
            bn = bn.Subtract(new Org.BouncyCastle.Math.BigInteger("1"));
            if (y.CompareTo(bn) > 0)
            {
                LibRTMPLogger.Log(LibRTMPLogLevel.Warning, "[CDR.LibRTMP.RTMPHelper.IsValidPublicKey] DH public key must be at most p-2");
                return false;
            }


            // Verify with Sophie-Germain prime
            //
            // This is a nice test to make sure the public key position is calculated
            // correctly. This test will fail in about 50% of the cases if applied to
            // random data.
            bn = y.ModPow(q, p);
            if (bn.CompareTo(new Org.BouncyCastle.Math.BigInteger("1")) != 0)
            {
                LibRTMPLogger.Log(LibRTMPLogLevel.Warning, "[CDR.LibRTMP.RTMPHelper.IsValidPublicKey] DH public key does not fulfill y^q mod p = 1");
                return false;
            }

            return true;
        }
Exemplo n.º 42
0
        public static int DecodeMpiFromBytes(byte[] mpi_byte_array, int start_index, ref Org.BouncyCastle.Math.BigInteger out_big_int)
        {
            byte[] _out_byte_array = null;
            int _next_start_index = DecodeMpiFromBytesBE(mpi_byte_array, start_index, ref _out_byte_array);

            out_big_int = new Org.BouncyCastle.Math.BigInteger(1, _out_byte_array);

            return _next_start_index;
        }
Exemplo n.º 43
0
        public static string PrivHexToPubHex(string PrivHex)
        {
            byte[] hex = Bitcoin.ValidateAndGetHexPrivateKey(0x00, PrivHex);
            if (hex == null) throw new ApplicationException("Invalid private hex key");
            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            Org.BouncyCastle.Math.BigInteger Db = new Org.BouncyCastle.Math.BigInteger(hex);
            ECPoint dd = ps.G.Multiply(Db);

            byte[] pubaddr = new byte[65];
            byte[] Y = dd.Y.ToBigInteger().ToByteArray();
            Array.Copy(Y, 0, pubaddr, 64 - Y.Length + 1, Y.Length);
            byte[] X = dd.X.ToBigInteger().ToByteArray();
            Array.Copy(X, 0, pubaddr, 32 - X.Length + 1, X.Length);
            pubaddr[0] = 4;

            return Bitcoin.ByteArrayToString(pubaddr);
        }
Exemplo n.º 44
0
        public static string GetPublicKey(string privateKey)
        {
            var hexPrivateKey = ReferenceLib.ValidateAndGetHexPrivateKey(privateKey, 0x00);
            if (hexPrivateKey == null)
                throw new Exception("error");

            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            Org.BouncyCastle.Math.BigInteger Db = new Org.BouncyCastle.Math.BigInteger(hexPrivateKey);
            ECPoint dd = ps.G.Multiply(Db);

            byte[] pubaddr = new byte[65];
            byte[] Y = dd.Y.ToBigInteger().ToByteArray();
            Array.Copy(Y, 0, pubaddr, 64 - Y.Length + 1, Y.Length);
            byte[] X = dd.X.ToBigInteger().ToByteArray();
            Array.Copy(X, 0, pubaddr, 32 - X.Length + 1, X.Length);
            pubaddr[0] = 4;

            var publicKey = ByteArrayToString(pubaddr);

            return publicKey;
        }
Exemplo n.º 45
-1
 /// <summary>
 /// To the bouncy castle big integer.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <returns></returns>
 public static Org.BouncyCastle.Math.BigInteger ToBouncyBigInteger(this BigInteger value)
 {
     var bytes = Utility.GetBytes(value);
     var bigint = new Org.BouncyCastle.Math.BigInteger(bytes);
     return bigint;
 }