Example #1
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));
        }
Example #2
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);
        }
Example #3
0
        private async Task <ECDsa> GetECDsaAsync(CancellationToken cancel)
        {
            string key;

            if (_Config.ApnSecret != null)
            {
                key = _Config.ApnSecret;
            }
            else
            {
                key = await File.ReadAllTextAsync(_Config.ApnSecretPath, cancel);
            }

            using (TextReader reader = new StringReader(key))
            {
                var ecPrivateKeyParameters = (ECPrivateKeyParameters)
                                             new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();

                Org.BouncyCastle.Math.EC.ECPoint q =
                    ecPrivateKeyParameters.Parameters.G
                    .Multiply(ecPrivateKeyParameters.D).Normalize();

                var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();


                var msEcp = new ECParameters();
                msEcp.Curve = ECCurve.NamedCurves.nistP256;
                msEcp.Q.X   = q.AffineXCoord.GetEncoded();
                msEcp.Q.Y   = q.AffineYCoord.GetEncoded();
                msEcp.D     = d;
                return(ECDsa.Create(msEcp));
            }
        }
Example #4
0
        protected string EncodeECPointHexCompressed(Org.BouncyCastle.Math.EC.ECPoint point)
        {
            var        compressedPoint = point.GetEncoded(true);
            BigInteger biInt           = new BigInteger(compressedPoint);

            return(biInt.ToString(16));
        }
Example #5
0
        internal static ECPublicKeyParameters GetECPublicKeyParametersFromString(string publicKeyString)
        {
            var publicKeyBytes = GetPublicKeyBytesWithoutCheckSum(publicKeyString);

            Org.BouncyCastle.Math.EC.ECPoint q = curve.DecodePoint(publicKeyBytes);
            return(new ECPublicKeyParameters(q, domainParams));
        }
Example #6
0
        private ECPublicKeyParameters GetPublicKeyParameters(ECDiffieHellmanPublicKey publicKey)
        {
            byte[] ecdhBlob = publicKey.ToByteArray();

            int    keySize;
            string magic = Encoding.ASCII.GetString(ecdhBlob, 0, 4);

            if (magic.Equals("ECK1"))
            {
                keySize = 256;
            }
            else if (magic.Equals("ECK3"))
            {
                keySize = 384;
            }
            else if (magic.Equals("ECK5"))
            {
                keySize = 521;
            }
            else
            {
                throw new Exception("Unknown public key type");
            }
            if (keySize != _keySize)
            {
                throw new Exception("Public key size doesn't match our key size");
            }

            byte[] encoded = new byte[1 + ecdhBlob.Length - 8];
            encoded[0] = 0x04;
            Buffer.BlockCopy(ecdhBlob, 8, encoded, 1, ecdhBlob.Length - 8);
            Org.BouncyCastle.Math.EC.ECPoint ecPoint = _domainParameters.Curve.DecodePoint(encoded);
            return(new ECPublicKeyParameters(ecPoint, _domainParameters));
        }
        private static string EncodeECPointHexCompressed(Org.BouncyCastle.Math.EC.ECPoint point)
        {
            BigInteger x = point.XCoord.ToBigInteger();
            BigInteger y = point.YCoord.ToBigInteger();

            return(x.ToString(16) + Convert.ToInt32(y.TestBit(0)));
        }
        /// <summary>
        /// Creates the challenge for the Chaum-Pedersen protocol, using the strong Fiat-Shamir transformation.
        /// Hashes all input and a fixed domain to create an unpredictable number. Used by the initiator and token service.
        /// </summary>
        /// <param name="G">Curve generator</param>
        /// <param name="P">Randomised point on curve</param>
        /// <param name="K">Public key K = k*G</param>
        /// <param name="Q">Signature Q = k*P</param>
        /// <param name="X">Commitment X = r*G</param>
        /// <param name="Y">Commitment Y = r*P</param>
        /// <returns>A random number uniquely based on all inputs</returns>
        public static BigInteger CreateChallenge(ECPoint G, ECPoint P, ECPoint K, ECPoint Q, ECPoint X, ECPoint Y)
        {
            // Encode the ECPoint inputs
            byte[]? GEncoded = G.GetEncoded();
            byte[]? PEncoded = P.GetEncoded();
            byte[]? KEncoded = K.GetEncoded();
            byte[]? QEncoded = Q.GetEncoded();
            byte[]? XEncoded = X.GetEncoded();
            byte[]? YEncoded = Y.GetEncoded();

            // Domain separation: make sure hash is independent of other systems
            string?domain = "AnonymousTokens";

            byte[]? domainEncoded = Encoding.ASCII.GetBytes(domain);

            // Using concat() is best for performance: https://stackoverflow.com/a/415396
            IEnumerable <byte> points = domainEncoded
                                        .Concat(GEncoded)
                                        .Concat(PEncoded)
                                        .Concat(KEncoded)
                                        .Concat(QEncoded)
                                        .Concat(XEncoded)
                                        .Concat(YEncoded);

            SHA256?    sha256    = SHA256.Create();
            BigInteger?hashAsInt = new BigInteger(sha256.ComputeHash(points.ToArray()));

            return(hashAsInt.Mod(G.Curve.Order));
        }
        public static string GetPublicKeyFromPrivateKey(string privateKey)
        {
            byte[] privateKeyBytes             = HexStringToByteArray(privateKey);
            Org.BouncyCastle.Math.EC.ECPoint q = domainParameters.G.Multiply(new BigInteger(privateKeyBytes));

            return(ToHexString(q.GetEncoded()));
        }
        private static void ExistingPrivateKeyToAddress(string privKeyHex) ///Gets Private Key and Makes it into an Address
        {
            BigInteger privateKey = new BigInteger(privKeyHex, 16);

            Org.BouncyCastle.Math.EC.ECPoint pubKey = GetPublicKeyFromPrivateKey(privateKey);
            string pubKeyCompressed = EncodeECPointHexCompressed(pubKey);
            string addr             = RipeMDHash(pubKeyCompressed);
        }
        public string EncodeECPointHexCompressed(ECPoint point)
        {
            BigInteger x = point.XCoord.ToBigInteger();

            BigInteger y = point.YCoord.ToBigInteger();

            return(x.ToString(16) + Convert.ToInt32(y.TestBit(0)));
        }
Example #12
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));
        }
        public string GetPublicKeyCompressed(string privateKeyString)
        {
            BigInteger privateKey = new BigInteger(privateKeyString, 16);
            ECPoint    pubKey     = GetPublicKeyFromPrivateKey(privateKey);

            string pubKeyCompressed = EncodeECPointHexCompressed(pubKey);

            return(pubKeyCompressed);
        }
Example #14
0
        //0x334B4345
        public static byte[] ConvertToNCryptEccPublicBlob(Org.BouncyCastle.Math.EC.ECPoint q)
        {
            var magic = new byte[] { 0x45, 0x43, 0x4B, 0x33 };
            var len   = new byte[] { 0x30, 0, 0, 0 };           // key length - 384 bit / 8

            var qx = q.AffineXCoord.GetEncoded();
            var qy = q.AffineYCoord.GetEncoded();

            return((new[] { magic, len, qx, qy }).SelectMany(_ => _).ToArray());
        }
        public string GetAddressFromPrivateKey(string privateKeyHex)
        {
            BigInteger privateKey = new BigInteger(privateKeyHex, 16);

            ECPoint publicKey = GetPublicKeyFromPrivateKey(privateKey);

            string pubKeyCompressed = EncodeECPointHexCompressed(publicKey);

            string address = this.CalcRipeMD160(pubKeyCompressed);

            return(address);
        }
Example #16
0
        internal Secp256k1PublicKey(Org.BouncyCastle.Asn1.X9.X9ECParameters k1Params, Org.BouncyCastle.Math.EC.ECPoint publicKey)
        {
            this.publicKey = publicKey;
            this.signer    = new Org.BouncyCastle.Crypto.Signers.ECDsaSigner(
                new Org.BouncyCastle.Crypto.Signers.HMacDsaKCalculator(
                    new Org.BouncyCastle.Crypto.Digests.Sha256Digest()));
            var parameters = new Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters(
                this.publicKey,
                new Org.BouncyCastle.Crypto.Parameters.ECDomainParameters(k1Params.Curve, k1Params.G, k1Params.N, k1Params.H));

            signer.Init(false, parameters);
        }
Example #17
0
        private static AsymmetricCipherKeyPair KeyFromPrivate(string privateKey)
        {
            BigInteger privateKeyInt = new BigInteger(privateKey, 16);

            X9ECParameters     curve  = SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

            ECPoint q = domain.G.Multiply(privateKeyInt);
            ECPrivateKeyParameters privateKeyParam = new ECPrivateKeyParameters(privateKeyInt, domain);
            ECPublicKeyParameters  publicKeyParam  = new ECPublicKeyParameters(q, domain);

            return(new AsymmetricCipherKeyPair(publicKeyParam, privateKeyParam));
        }
Example #18
0
        /// <summary>
        /// Gets the public key from the private key.
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string GetPublicKey(string privateKey)
        {
            BigInteger privateKeyInt = new BigInteger(privateKey, 16);

            X9ECParameters     curve  = SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

            ECPoint q = domain.G.Multiply(privateKeyInt);

            byte[] bytes = q.GetEncoded();

            return(Hex.ToHexString(bytes));
        }
        public bool VerifySignatureUsingSecp256k1(byte[] publicKey, BigInteger[] signature, byte[] message)
        {
            X9ECParameters parameters          = SecNamedCurves.GetByName("secp256k1");
            var            ecParameters        = new ECDomainParameters(parameters.Curve, parameters.G, parameters.N, parameters.H);
            ECPoint        q                   = ecParameters.Curve.DecodePoint(publicKey);
            var            publicKeyParameters = new ECPublicKeyParameters(q, ecParameters);

            var signer = new ECDsaSigner();

            signer.Init(false, publicKeyParameters);

            return(signer.VerifySignature(message, signature[0].Abs(), signature[1].Abs()));
        }
Example #20
0
        public Secp256k1PublicKey(ReadOnlySpan <byte> key)
        {
            var k1Params = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");

            this.publicKey = k1Params.Curve.DecodePoint(key.ToArray());
            this.signer    = new Org.BouncyCastle.Crypto.Signers.ECDsaSigner(
                new Org.BouncyCastle.Crypto.Signers.HMacDsaKCalculator(
                    new Org.BouncyCastle.Crypto.Digests.Sha256Digest()));
            var parameters = new Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters(
                this.publicKey,
                new Org.BouncyCastle.Crypto.Parameters.ECDomainParameters(k1Params.Curve, k1Params.G, k1Params.N, k1Params.H));

            signer.Init(false, parameters);
        }
        public void SetUpSimpleCurve()
        {
            OpenECCSimpleCurve = new OpenECC.WeierstrassCurve(new System.Numerics.BigInteger(4), new System.Numerics.BigInteger(20), new System.Numerics.BigInteger(29));
            OpenECCSimplePoint1 = new OpenECC.WeierstrassCurvePoint(new System.Numerics.BigInteger(5), new System.Numerics.BigInteger(22), OpenECCSimpleCurve);
            OpenECCSimplePoint2 = new OpenECC.WeierstrassCurvePoint(new System.Numerics.BigInteger(16), new System.Numerics.BigInteger(27), OpenECCSimpleCurve);
            OpenECCSimplePoint3 = new OpenECC.WeierstrassCurvePoint(new System.Numerics.BigInteger(13), new System.Numerics.BigInteger(6), OpenECCSimpleCurve);
            OpenECCSimplePoint4 = new OpenECC.WeierstrassCurvePoint(new System.Numerics.BigInteger(14), new System.Numerics.BigInteger(6), OpenECCSimpleCurve);

            BCSimpleCurve = new Org.BouncyCastle.Math.EC.FpCurve(new Org.BouncyCastle.Math.BigInteger("29"), new Org.BouncyCastle.Math.BigInteger("4"), new Org.BouncyCastle.Math.BigInteger("20"));
            BCSimplePoint1 = BCSimpleCurve.CreatePoint(new Org.BouncyCastle.Math.BigInteger("5"), new Org.BouncyCastle.Math.BigInteger("22"), false);
            BCSimplePoint2 = BCSimpleCurve.CreatePoint(new Org.BouncyCastle.Math.BigInteger("16"), new Org.BouncyCastle.Math.BigInteger("27"), false);
            BCSimplePoint3 = BCSimpleCurve.CreatePoint(new Org.BouncyCastle.Math.BigInteger("13"), new Org.BouncyCastle.Math.BigInteger("6"), false);
            BCSimplePoint4 = BCSimpleCurve.CreatePoint(new Org.BouncyCastle.Math.BigInteger("14"), new Org.BouncyCastle.Math.BigInteger("6"), false);
        }
        public void SetUpSecp256k1()
        {
            //Set up OpenECC Curve
            OpenECCSecp256k1 = OpenECC.CurveFactory.secp256k1;
            OpenECCGenerator = OpenECCSecp256k1.Generator;
            OpenECCPoint1 = OpenECCGenerator * 3;
            OpenECCPoint2 = OpenECCGenerator * 5;

            //Set up BouncyCastle curve
            var bc_stuff = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            BCSecp256k1 = bc_stuff.Curve;
            BCGenerator = bc_stuff.G;
            BCPoint1 = BCGenerator.Multiply(new Org.BouncyCastle.Math.BigInteger("3"));
            BCPoint2 = BCGenerator.Multiply(new Org.BouncyCastle.Math.BigInteger("5"));
        }
Example #23
0
        public static Key Deserialize(IEnumerable <byte> payload)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            var c      = SecNamedCurves.GetByName("secp256k1");
            var domain = new ECDomainParameters(c.Curve, c.G, c.N, c.H);

            Org.BouncyCastle.Math.EC.ECCurve curve = domain.Curve;
            Org.BouncyCastle.Math.EC.ECPoint q     = curve.DecodePoint(payload.ToArray());
            var publicKey = new ECPublicKeyParameters(q, domain);

            return(new Key(null, publicKey));
        }
        private static string CreateAndSignTransaction(string recipientAddress, long value,
                                                       int fee, string data, string iso8601datetime, string senderPrivKeyHex) ///Creates and Signs Transaction
        {
            BigInteger privateKey = new BigInteger(senderPrivKeyHex, 16);

            Org.BouncyCastle.Math.EC.ECPoint pubKey = GetPublicKeyFromPrivateKey(privateKey);
            string senderPubKeyCompressed           = EncodeECPointHexCompressed(pubKey);

            string senderAddress = RipeMDHash(senderPubKeyCompressed);

            var tran = new //Creates unsigned Transaction
            {
                from = senderAddress,
                to   = recipientAddress,
                value,
                fee,
                dateCreated = iso8601datetime,
                data,
                senderPubKey = senderPubKeyCompressed,
            };
            string tranJson = JsonConvert.SerializeObject(tran);

            byte[] tranHash = CalcSHA256(tranJson);

            BigInteger[] tranSignature = SignData(privateKey, tranHash);

            var tranSigned = new //Signed Transaction
            {
                from         = senderAddress,
                to           = recipientAddress,
                senderPubKey = senderPubKeyCompressed,
                value,
                fee,
                data,
                dateCreated     = iso8601datetime,
                senderSignature = new string[]
                {
                    tranSignature[0].ToString(16),
                    tranSignature[1].ToString(16)
                }
            };

            string signedTranJson = JsonConvert.SerializeObject(tranSigned, Formatting.Indented);

            Print("Transaction Hash: " + BytesToHex(tranHash));
            return(signedTranJson);
        }
Example #25
0
        private static PublicKey toECDSAPublicKey(byte[] keyBytes, ECKeyInfo keyinfo) // throws IOException, GeneralSecurityException
        {
            DNSInput @in = new DNSInput(keyBytes);

            // RFC 6605 Section 4
            Org.BouncyCastle.Math.BigInteger x = Helpers.readBigInteger(@in, keyinfo.length);
            Org.BouncyCastle.Math.BigInteger y = Helpers.readBigInteger(@in, keyinfo.length);


            // Org.BouncyCastle.Asn1.X9.X9ECParameters ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp521r1");
            // Org.BouncyCastle.Asn1.X9.X9ECParameters ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256r1");
            // Org.BouncyCastle.Asn1.X9.X9ECParameters p = Org.BouncyCastle.Asn1.X9.X962NamedCurves.GetByOid(Org.BouncyCastle.Asn1.X9.X9ObjectIdentifiers.Prime239v1);
            // Org.BouncyCastle.Asn1.X9.X9ECParameters p = Org.BouncyCastle.Asn1.X9.X962NamedCurves.GetByOid(Org.BouncyCastle.Asn1.X9.X9ObjectIdentifiers.ECDsaWithSha512);
            // Org.BouncyCastle.Asn1.X9.X9ECParameters ecP = Org.BouncyCastle.Asn1.Nist.NistNamedCurves.GetByName("curveName");
            // Org.BouncyCastle.Math.EC.FpCurve c = (Org.BouncyCastle.Math.EC.FpCurve)ecP.Curve;


            // Org.BouncyCastle.Asn1.X9.X9ECParameters p = Org.BouncyCastle.Asn1.X9.X962NamedCurves.GetByOid(Org.BouncyCastle.Asn1.X9.X9ObjectIdentifiers.ECDsaWithSha512);
            // Org.BouncyCastle.Math.EC.ECCurve c = p.Curve;
            // Org.BouncyCastle.Crypto.Parameters.ECDomainParameters domain = new Org.BouncyCastle.Crypto.Parameters.ECDomainParameters(c, p.G, p.N, p.H);
            // Org.BouncyCastle.Math.EC.ECPoint q = new Org.BouncyCastle.Math.EC.FpPoint(c, c.FromBigInteger(x), c.FromBigInteger(y));
            // Org.BouncyCastle.Math.EC.ECPoint q = c.CreatePoint(x, 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.Security.PublicKeyFactory.CreateKey(Org.BouncyCastle.X509.SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicParams));

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

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

            return(PublicKey.CreateInstance(publicParams));
        }
        public static string GeneratePkcs10
            (PrivateKey privKey, PublicKey pubKey, string commonName, string organization, string organizationUnit, string city, string state,
            string countryIso2Characters, string email)
        {
            try
            {
                Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math.BigInteger(privKey.ByteArray.Reverse().ToArray());

                SecureRandom       secureRandom = new SecureRandom();
                X9ECParameters     curve        = SecNamedCurves.GetByName("secp256k1");
                ECDomainParameters domain       = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

                Org.BouncyCastle.Math.EC.ECPoint q = domain.G.Multiply(d);

                var priv = new ECPrivateKeyParameters("EC", d, SecObjectIdentifiers.SecP256k1);
                var pub  = new ECPublicKeyParameters("EC", q, SecObjectIdentifiers.SecP256k1);

                Dictionary <DerObjectIdentifier, string> attrs = new Dictionary <DerObjectIdentifier, string>();

                attrs.Add(X509Name.O, organization);
                attrs.Add(X509Name.OU, organizationUnit);
                attrs.Add(X509Name.EmailAddress, email);
                attrs.Add(X509Name.L, city);
                attrs.Add(X509Name.ST, state);
                attrs.Add(X509Name.C, countryIso2Characters);
                attrs.Add(X509Name.CN, commonName);

                var subject = new X509Name(attrs.Keys.ToList(), attrs.Values.ToList());

                var pkcs10CertificationRequest = new Pkcs10CertificationRequest("SHA1withECDSA", subject, pub, null, priv);
                var base64csr = Convert.ToBase64String(pkcs10CertificationRequest.GetEncoded());

                var width = 64;
                for (int i = width; i < base64csr.Length; i += width + 1)
                {
                    base64csr = base64csr.Insert(i, "\n");
                }

                return(base64csr);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #27
0
        public ICipherParameters DecodePublicKey(byte[] encodedPublicKey)
        {
            try
            {
                X9ECParameters     curve = SecNamedCurves.GetByOid(_curve);
                ECPoint            point = curve.Curve.DecodePoint(encodedPublicKey);
                ECDomainParameters ecP   = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

                return(new ECPublicKeyParameters(point, ecP));
            }
            catch (InvalidKeySpecException exception)
            {
                throw new U2fException(Resources.SignatureError, exception);
            }
            catch (Exception exception)
            {
                throw new U2fException(ErrorDecodingPublicKey, exception);
            }
        }
Example #28
0
        private static ECDsa LoadPrivateKey(byte[] key)
        {
            BigInteger     privKeyInt = new BigInteger(+1, key);
            X9ECParameters parameters = SecNamedCurves.GetByName("secp256k1");
            ECPoint        ecPoint    = parameters.G.Multiply(privKeyInt);

            byte[] privKeyX = ecPoint.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned();
            byte[] privKeyY = ecPoint.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned();

            return(ECDsa.Create(new ECParameters
            {
                Curve = ECCurve.CreateFromFriendlyName("secp256k1"),
                D = privKeyInt.ToByteArrayUnsigned(),
                Q = new System.Security.Cryptography.ECPoint
                {
                    X = privKeyX,
                    Y = privKeyY
                }
            }));
        }
Example #29
0
        private string PrivateKeyHexToPublicKeyHex(string privateKeyHex)
        {
            byte[] privateKeyBytes = this.ValidateAndGetPrivateKeyBytes(privateKeyHex, 0x00);
            if (privateKeyBytes == null)
            {
                return(null);
            }

            X9ECParameters curves            = SecNamedCurves.GetByName("secp256k1");
            BigInteger     privateKeyInteger = new BigInteger(privateKeyBytes);
            ECPoint        p = curves.G.Multiply(privateKeyInteger);

            byte[] publicAddress = new byte[65];
            byte[] y             = p.Normalize().YCoord.ToBigInteger().ToByteArray();
            Array.Copy(y, 0, publicAddress, 64 - y.Length + 1, y.Length);
            byte[] x = p.Normalize().XCoord.ToBigInteger().ToByteArray();
            Array.Copy(x, 0, publicAddress, 32 - x.Length + 1, x.Length);
            publicAddress[0] = 4;

            return(this.ByteArrayToString(publicAddress));
        }
Example #30
0
        public static Key Deserialize(BigInteger publicKey, BigInteger privateKey)
        {
            if (publicKey == null)
            {
                throw new ArgumentNullException(nameof(publicKey));
            }

            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            var c      = SecNamedCurves.GetByName("secp256k1");
            var domain = new ECDomainParameters(c.Curve, c.G, c.N, c.H);

            Org.BouncyCastle.Math.EC.ECCurve curve = domain.Curve;
            Org.BouncyCastle.Math.EC.ECPoint q     = curve.DecodePoint(publicKey.ToByteArray());
            var pubK = new ECPublicKeyParameters(q, domain);
            var prK  = new ECPrivateKeyParameters(privateKey, domain);

            return(new Key(prK, pubK));
        }
Example #31
0
        /// <summary>
        /// Check ECDSA Signature (secp256r1)
        /// </summary>
        /// <param name="message">Message</param>
        /// <param name="signature">Signature</param>
        /// <param name="pubkey">Public Key</param>
        /// <returns>Bool</returns>
        public override bool VerifySignature(byte[] message, byte[] signature, byte[] pubkey)
        {
            byte[] fullpubkey = DecodePublicKey(pubkey, false, out System.Numerics.BigInteger x, out System.Numerics.BigInteger y);

            Org.BouncyCastle.Math.EC.ECPoint point = _curve.Curve.DecodePoint(fullpubkey);
            var keyParameters = new ECPublicKeyParameters(point, _domain);

            var signer = SignerUtilities.GetSigner("SHA256withECDSA");

            signer.Init(false, keyParameters);
            signer.BlockUpdate(message, 0, message.Length);

            if (signature.Length == 64)
            {
                signature = new DerSequence(
                    new DerInteger(new BigInteger(1, signature.Take(32).ToArray())),
                    new DerInteger(new BigInteger(1, signature.Skip(32).ToArray())))
                            .GetDerEncoded();
            }

            return(signer.VerifySignature(signature));
        }
Example #32
0
        static byte[] GetSharedKey(ECPrivateKeyParameters sigPrivKey, byte[] serverPubKey)
        {
            Console.WriteLine("Generating shared key!");

            var ecP = ECNamedCurveTable.GetByName("secp256k1");

            var domainParams = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());

            Org.BouncyCastle.Math.EC.ECPoint point = domainParams.Curve.DecodePoint(serverPubKey);

            ECPublicKeyParameters oEcPublicKeyParameters = new ECPublicKeyParameters(point, domainParams);

            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(sigPrivKey);

            var sharedKey = aKeyAgree.CalculateAgreement(oEcPublicKeyParameters).ToByteArray();

            Console.WriteLine($"{sharedKey.Length} bytes Created shared key ({ToHex(sharedKey)})");

            return(sharedKey);
        }