public static void Test()
        {
            string msg    = "StackOverflow test 123";
            string sig    = "IB7XjSi9TdBbB3dVUK4+Uzqf2Pqk71XkZ5PUsVUN+2gnb3TaZWJwWW2jt0OjhHc4B++yYYRy1Lg2kl+WaiF+Xsc=";
            string pubkey = "045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5";

            SHA256Managed sha256 = new SHA256Managed();

            byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(msg), 0, Encoding.UTF8.GetByteCount(msg));
            Console.WriteLine("Hash: " + ToHex(hash));

            byte[] tmpBytes = Convert.FromBase64String(sig);
            byte[] sigBytes = new byte[tmpBytes.Length - 1];
            Buffer.BlockCopy(tmpBytes, 1, sigBytes, 0, sigBytes.Length);

            int rec = (tmpBytes[0] - 27) & ~4;

            Console.WriteLine("Rec {0}", rec);

            ECPoint Q    = Recover(hash, sigBytes, rec);
            string  qstr = ToHex(Q.GetEncoded());

            Console.WriteLine("Q is same as supplied: " + qstr.Equals(pubkey));

            Console.WriteLine("Signature verified correctly: " + VerifySignature(Q.GetEncoded(), hash, sigBytes));
        }
Example #2
0
        /**
         * Test encoding with and without point compression.
         *
         * @param p
         *            The point to be encoded and decoded.
         */
        private void ImplTestEncoding(ECPoint p)
        {
            // Not Point Compression
            byte[]  unCompBarr = p.GetEncoded(false);
            ECPoint decUnComp  = p.Curve.DecodePoint(unCompBarr);

            AssertPointsEqual("Error decoding uncompressed point", p, decUnComp);

            // Point compression
            byte[]  compBarr = p.GetEncoded(true);
            ECPoint decComp  = p.Curve.DecodePoint(compBarr);

            AssertPointsEqual("Error decoding compressed point", p, decComp);
        }
Example #3
0
        /// <summary>
        ///     Creates a round 2 (zero-knowledge proof) DTO to send to the partner participant.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        ///     Prior round (1) has not been completed yet, or method may have been called more than once.
        /// </exception>
        public ECJpakeRound2 CreateRound2ToSend()
        {
            if (ProtocolState >= State.Round2Created)
            {
                throw new InvalidOperationException("Round 2 payload already created.");
            }
            if (ProtocolState < State.Round1Validated)
            {
                throw new InvalidOperationException("Round 1 payload must be validated prior to creating Round 2 payload.");
            }

            var s1 = new BigInteger(_passwordBytes);

            ECPoint    GA   = _gx1.Add(_gx3).Add(_gx4);
            BigInteger x2s1 = _x2.Multiply(s1).Mod(_domain.N);
            ECPoint    A    = BasePointMultiplier.Multiply(GA, x2s1);

            ECPoint    X2sV;
            BigInteger X2sR;

            CreateZeroKnowledgeProof(GA, x2s1, A, ParticipantId, out X2sV, out X2sR);

            var dto = new ECJpakeRound2 {
                ParticipantId = ParticipantId,
                A             = A.GetEncoded(),
                X2sV          = X2sV.GetEncoded(),
                X2sR          = X2sR.ToByteArray()
            };

            ProtocolState = State.Round2Created;
            return(dto);
        }
Example #4
0
        /// <summary>
        ///     Creates a round 1 (zero-knowledge proof) DTO to send to the partner participant.
        /// </summary>
        public ECJpakeRound1 CreateRound1ToSend()
        {
            Contract.Requires(ProtocolState < State.Round1Created, "Round 1 payload already created.");

            BigInteger x1 = BigInteger.CreateRandomInRange(BigInteger.One, _domain.N.Subtract(BigInteger.One),
                                                           EntropySupply);

            _x2  = BigInteger.CreateRandomInRange(BigInteger.One, _domain.N.Subtract(BigInteger.One), EntropySupply);
            _gx1 = BasePointMultiplier.Multiply(_domain.G, x1);
            _gx2 = BasePointMultiplier.Multiply(_domain.G, _x2);

            ECPoint    V1, V2;
            BigInteger r1, r2;

            CreateZeroKnowledgeProof(_domain.G, x1, _gx1, ParticipantId, out V1, out r1);
            CreateZeroKnowledgeProof(_domain.G, _x2, _gx2, ParticipantId, out V2, out r2);

            var dto = new ECJpakeRound1 {
                ParticipantId = ParticipantId,
                GX1           = _gx1.GetEncoded(),
                X1V           = V1.GetEncoded(),
                X1R           = r1.ToByteArray(),
                GX2           = _gx2.GetEncoded(),
                X2V           = V2.GetEncoded(),
                X2R           = r2.ToByteArray()
            };

            ProtocolState = State.Round1Created;
            return(dto);
        }
Example #5
0
 protected ECPublicBcpgKey(
     DerObjectIdentifier oid,
     ECPoint point)
 {
     this.point = new BigInteger(1, point.GetEncoded(false));
     this.oid   = oid;
 }
Example #6
0
        public void TestDecode()
        {
            var curve = new FPCurve(
                new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
                new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16),       // a
                new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16));      // b

            ECPoint p = curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"));

            if (!p.X.ToBigInteger().Equals(new BigInteger("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16)))
            {
                Fail("x uncompressed incorrectly");
            }

            if (!p.Y.ToBigInteger().Equals(new BigInteger("7192b95ffc8da78631011ed6b24cdd573f977a11e794811", 16)))
            {
                Fail("y uncompressed incorrectly");
            }

            byte[] encoding = p.GetEncoded();

            if (!AreEqual(encoding, Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")))
            {
                Fail("point compressed incorrectly");
            }
        }
Example #7
0
 public AnonymousTokenResponse(string kid, ECPoint signedPoint, BigInteger proofChallenge, BigInteger proofResponse)
 {
     Kid            = kid;
     SignedPoint    = Convert.ToBase64String(signedPoint.GetEncoded());
     ProofChallenge = Convert.ToBase64String(proofChallenge.ToByteArray());
     ProofResponse  = Convert.ToBase64String(proofResponse.ToByteArray());
 }
Example #8
0
        /// <summary>
        ///     Calculate the aggregated commitment
        /// </summary>
        /// <param name="commitments">An array listToTable of commitments from each signer</param>
        /// <param name="bitmapCommitments">Commitments the bitmap of considered commitments from the whole listToTable</param>
        /// <returns>the aggregated commitment</returns>
        public virtual byte[] AggregateCommitments(List <byte[]> commitments, long bitmapCommitments)
        {
            Guard.NotNull(commitments, nameof(commitments));
            Guard.NotLessThanOrEqualTo(commitments.Count, 0, nameof(commitments));

            var     idx = 0;
            ECPoint aggregatedCommitment = null;
            var     result = new byte[0];

            foreach (var commitment in commitments)
            {
                if (0 != ((1 << idx) & bitmapCommitments))
                {
                    // aggregate the commits
                    var decodedCommitment = _secp256k1.Parameters.Curve.DecodePoint((byte[])commitment.Clone());
                    aggregatedCommitment = null == aggregatedCommitment
                        ? decodedCommitment
                        : aggregatedCommitment.Add(decodedCommitment);
                }

                idx++;
            }

            if (null != aggregatedCommitment)
            {
                result = aggregatedCommitment.GetEncoded(true);
            }
            return(result);
        }
Example #9
0
        public static BigInteger PublicKeyFromPrivate(BigInteger privKey)
        {
            ECPoint point = PublicPointFromPrivate(privKey);

            byte[] encoded = point.GetEncoded(false);
            return(new BigInteger(1, Arrays.CopyOfRange(encoded, 1, encoded.Length))); // remove prefix
        }
Example #10
0
        private byte[] Encrypt(byte[] input, int inOff, int inLen)
        {
            byte[] c2 = new byte[inLen];

            Array.Copy(input, inOff, c2, 0, c2.Length);

            ECMultiplier multiplier = CreateBasePointMultiplier();

            byte[]  c1;
            ECPoint kPB;

            do
            {
                BigInteger k = NextK();

                ECPoint c1P = multiplier.Multiply(mECParams.G, k).Normalize();

                c1 = c1P.GetEncoded(false);

                kPB = ((ECPublicKeyParameters)mECKey).Q.Multiply(k).Normalize();

                Kdf(mDigest, kPB, c2);
            }while (NotEncrypted(c2, input, inOff));

            AddFieldElement(mDigest, kPB.AffineXCoord);
            mDigest.BlockUpdate(input, inOff, inLen);
            AddFieldElement(mDigest, kPB.AffineYCoord);

            byte[] c3 = DigestUtilities.DoFinal(mDigest);

            return(Arrays.ConcatenateAll(c1, c2, c3));
        }
Example #11
0
        /// <summary>
        /// calculates the signature multipled by the generator
        /// point, for an arbitrary message based on pubkey R and pubkey A.
        /// Calculates P = pubR - h(msg, pubR)pubA.
        /// This is used when building settlement transactions and determining the pubkey
        /// to the oracle's possible signatures beforehand. Can be calculated with just
        /// public keys, so by anyone.
        /// </summary>
        /// <param name="oraclePubA">The oracle's public key</param>
        /// <param name="oraclePubR">The oracle's R-point (public key to the one-time signing key)</param>
        /// <param name="message">The message to compute the signature pubkey for</param>
        public static byte[] ComputeSignaturePubKey(byte[] oraclePubA, byte[] oraclePubR, byte[] message)
        {
            ECPoint A = curve.Curve.DecodePoint(oraclePubA).Normalize();
            ECPoint R = curve.Curve.DecodePoint(oraclePubR).Normalize();

            byte[] rX = R.XCoord.ToBigInteger().ToByteArray();
            while (rX[0] == (byte)0)
            {
                rX = rX.Skip(1).ToArray();
            }
            Sha256Digest myHash = new Sha256Digest();

            myHash.BlockUpdate(message, 0, message.Length);
            myHash.BlockUpdate(rX, 0, rX.Length);
            byte[] e = new byte[myHash.GetDigestSize()];
            myHash.DoFinal(e, 0);

            BigInteger bigE = BigIntegerFromBytes(e);

            A = A.Multiply(bigE).Normalize();
            var y = A.YCoord.ToBigInteger().Negate();

            y = y.Mod(p);
            A = curve.Curve.CreatePoint(A.XCoord.ToBigInteger(), y).Normalize();
            A = A.Add(R).Normalize();
            return(A.GetEncoded(true));
        }
        private static BigInteger _recoverFromSignature(int recId, ECSignature sig, byte[] msg, ECDomainParameters parameters)
        {
            BigInteger n = parameters.N;
            BigInteger i = new BigInteger((recId / 2).ToString());
            BigInteger x = sig.r.Add(i.Multiply(n));

            if (x.CompareTo(_prime) >= 0)
            {
                return(null);
            }

            ECPoint R = _decompressKey(x, (recId & 1) == 1, parameters.Curve);

            if (!(R.Multiply(n)).IsInfinity)
            {
                return(null);
            }

            BigInteger e = _bytesToInt(msg);

            BigInteger eInv = (BigInteger.Zero.Subtract(e));

            eInv = n.DivideAndRemainder(eInv)[1];
            BigInteger rInv     = sig.r.ModInverse(n);
            BigInteger srInv    = rInv.Multiply(sig.s).DivideAndRemainder(n)[1];
            BigInteger eInvrInv = (rInv.Multiply(eInv)).DivideAndRemainder(n)[1];

            ECPoint q = ((parameters.G).Multiply(eInvrInv)).Add(R.Multiply(srInv));

            byte[] bytes    = q.GetEncoded(false);
            byte[] retBytes = new byte[bytes.Length - 1];
            Array.Copy(bytes, 1, retBytes, 0, bytes.Length - 1);
            return(_bytesToInt(retBytes));
        }
Example #13
0
        /// <summary>
        ///     Calculates the hash for a zero-knowledge proof.
        /// </summary>
        private BigInteger Hash(ECPoint generator, ECPoint V, ECPoint X, string participantId)
        {
            _digest.Reset();

            // Each item is prefixed with its length as a little-endian 4-byte unsigned integer
            var lengthPrefix = new byte[4];

            byte[] generatorBytes = generator.GetEncoded();
            Pack.UInt32_To_LE((uint)generatorBytes.Length, lengthPrefix);
            _digest.BlockUpdate(lengthPrefix, 0, 4);
            _digest.BlockUpdate(generatorBytes, 0, generatorBytes.Length);

            byte[] vBytes = V.GetEncoded();
            Pack.UInt32_To_LE((uint)vBytes.Length, lengthPrefix);
            _digest.BlockUpdate(lengthPrefix, 0, 4);
            _digest.BlockUpdate(vBytes, 0, vBytes.Length);

            byte[] xBytes = X.GetEncoded();
            Pack.UInt32_To_LE((uint)xBytes.Length, lengthPrefix);
            _digest.BlockUpdate(lengthPrefix, 0, 4);
            _digest.BlockUpdate(xBytes, 0, xBytes.Length);

            byte[] idBytes = Encoding.UTF8.GetBytes(participantId);
            Pack.UInt32_To_LE((uint)idBytes.Length, lengthPrefix);
            _digest.BlockUpdate(lengthPrefix, 0, 4);
            _digest.BlockUpdate(idBytes, 0, idBytes.Length);

            var hash = new byte[_digest.OutputSize];

            _digest.DoFinal(hash, 0);

            return(new BigInteger(hash));
        }
        /// <summary>
        /// Computes the public key from the private key.
        /// </summary>
        protected override byte[] ComputePublicKey()
        {
            var     ps    = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            ECPoint point = ps.G;

            Org.BouncyCastle.Math.BigInteger Db = new Org.BouncyCastle.Math.BigInteger(1, _privKey);
            ECPoint dd = point.Multiply(Db);


            if (IsCompressedPoint)
            {
                dd = ps.Curve.CreatePoint(dd.X.ToBigInteger(), dd.Y.ToBigInteger(), true);
                return(dd.GetEncoded());
            }
            else
            {
                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(pubaddr);
            }
        }
Example #15
0
        public static String Encrypt(byte[] publicKey, byte[] data)
        {
            if (null == publicKey || publicKey.Length == 0)
            {
                return(null);
            }
            if (data == null || data.Length == 0)
            {
                return(null);
            }

            byte[] source = new byte[data.Length];
            Array.Copy(data, 0, source, 0, data.Length);

            Cipher cipher = new Cipher();
            SM2    sm2    = SM2.Instance;

            ECPoint userKey = sm2.ecc_curve.DecodePoint(publicKey);

            ECPoint c1 = cipher.Init_enc(sm2, userKey);

            cipher.Encrypt(source);

            byte[] c3 = new byte[32];
            cipher.Dofinal(c3);

            String sc1 = Encoding.Default.GetString(Hex.Encode(c1.GetEncoded()));
            String sc2 = Encoding.Default.GetString(Hex.Encode(source));
            String sc3 = Encoding.Default.GetString(Hex.Encode(c3));

            return((sc1 + sc2 + sc3).ToUpper());
        }
Example #16
0
        /// <summary>
        /// 公钥加密算法,利用下一个用户的公钥进行加密
        /// </summary>
        /// <param name="sm2">sm2对象</param>
        /// <param name="msg">要加密的消息</param>
        /// <param name="ppk">目的签名者的公钥文件夹路径</param>
        /// <param name="id">加密后消息存入的文件夹(最好不存起来)</param>
        public string[] Test_sm2_cipher(SM2 sm2, string msg, string ppk)
        {
            byte[] data = Encoding.Default.GetBytes(msg);//将信息转化为比特

            // 加密过程
            ECPoint userKey = null;

            byte[] key = null;

            ReadpublicKey(out key, ppk);              //读取解密者的公钥
            userKey = sm2.ecc_curve.DecodePoint(key); //把字节形的转化为Ecpoint
            System.String sdata = new UTF8Encoding().GetString(Hex.Encode(data));

            SM2.Cipher cipher = new SM2.Cipher();
            ECPoint    c1     = cipher.Init_enc(sm2, userKey); //调用Init_enc方法

            byte[]        bc1  = c1.GetEncoded();              //将c1的数据类型转换成比特串
            System.String sbc1 = new UTF8Encoding().GetString(Hex.Encode(bc1));

            cipher.Encrypt(data);

            System.String sc2 = new UTF8Encoding().GetString(Hex.Encode(data));
            byte[]        c3  = new byte[32];
            cipher.Dofinal(c3);
            System.String sc3 = new UTF8Encoding().GetString(Hex.Encode(c3));

            string[] cc = { sbc1, sc2, sc3 };
            return(cc);
        }
Example #17
0
        public static string EncodeECPointHexCompressed(ECPoint point)
        {
            var        compressedPoint = point.GetEncoded(true);
            BigInteger biInt           = new BigInteger(compressedPoint);

            return(biInt.ToString(16));
        }
        private void calcPubKey(bool comp)
        {
            ECPoint point = ecParams.G.Multiply(new BigInteger(1, privKey));

            this.pubKey = point.GetEncoded();
            compress(comp);
        }
Example #19
0
        /**
         * @param privateKey hex string without 0x
         * @return
         */
        public static string GetPublicKeyFromPrivateKey(string privateKey, bool compressed)
        {
            BigInteger bigInteger = new BigInteger(privateKey, 16);
            ECPoint    point      = GetPublicPointFromPrivate(bigInteger);

            return(ByteUtil.ByteArrayToHexString(point.GetEncoded(compressed)));
        }
Example #20
0
        public static BigInteger PublicKeyFromPrivate(BigInteger privKey)
        {
            ECPoint point = publicPointFromPrivate(privKey);

            byte[] encoded = point.GetEncoded(false);
            return(new BigInteger(1, encoded.Skip(1).ToArray()));  // remove prefix
        }
Example #21
0
        public virtual ECPoint Init_enc(SM2CryptoServiceProvider sm2, ECPoint userKey)
        {
            //BigInteger k = null;
            //ECPoint c1 = null;

            //AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.GenerateKeyPair();
            //ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.Private;
            //ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.Public;
            //k = ecpriv.D;
            //c1 = ecpub.Q;

            //p2 = userKey.Multiply(k);
            //Reset();

            //return c1;

            var keySTR = userKey.GetEncoded().byteToHex();

            if (keySTR.Length > 64)
            {
                keySTR = keySTR.Substring(0, 64);
            }
            BigInteger k  = new BigInteger(keySTR, 16);  //ecpriv.getD();
            ECPoint    c1 = sm2.ecc_point_g.Multiply(k); //ecpub.getQ();

            this.p2 = userKey.Multiply(k);
            Reset();
            return(c1);
        }
Example #22
0
        /// <summary>
        /// Derives the public key to a private key
        /// </summary>
        /// <param name="privateKey">The private key to derive the public key for</param>
        public static byte[] PublicKeyFromPrivateKey(byte[] privateKey)
        {
            BigInteger d = BigIntegerFromBytes(privateKey);

            ECPoint q = domain.G.Multiply(d).Normalize();

            return(q.GetEncoded(true));
        }
Example #23
0
 public static byte[] ComputePublicKey(byte[] publicGenBytes, uint accountNumber)
 {
     ECPoint rootPubPoint = Secp256K1.Curve().DecodePoint(publicGenBytes);
     BigInteger scalar = ComputeScalar(publicGenBytes, accountNumber);
     ECPoint point = Secp256K1.BasePoint().Multiply(scalar);
     ECPoint offset = rootPubPoint.Add(point);
     return offset.GetEncoded(true);
 }
Example #24
0
 public static BigInteger ComputeSecretKey(
     BigInteger privateGen,
     uint accountNumber)
 {
     ECPoint publicGen = ComputePublicGenerator(privateGen);
     return ComputeScalar(publicGen.GetEncoded(true), accountNumber)
                     .Add(privateGen).Mod(Secp256K1.Order());
 }
        public static ECPoint ECDSA_SIG_recover_key_GFp(BigInteger[] sig, byte[] hash, int recid, bool check)
        {
            X9ECParameters ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            int            i        = recid / 2;

            Console.WriteLine("r: " + ToHex(sig[0].ToByteArrayUnsigned()));
            Console.WriteLine("s: " + ToHex(sig[1].ToByteArrayUnsigned()));

            BigInteger order = ecParams.N;
            BigInteger field = (ecParams.Curve as FpCurve).Q;
            BigInteger x     = order.Multiply(new BigInteger(i.ToString())).Add(sig[0]);

            if (x.CompareTo(field) >= 0)
            {
                throw new Exception("X too large");
            }

            Console.WriteLine("Order: " + ToHex(order.ToByteArrayUnsigned()));
            Console.WriteLine("Field: " + ToHex(field.ToByteArrayUnsigned()));

            byte[] compressedPoint = new Byte[x.ToByteArrayUnsigned().Length + 1];
            compressedPoint[0] = (byte)(0x02 + (recid % 2));
            Buffer.BlockCopy(x.ToByteArrayUnsigned(), 0, compressedPoint, 1, compressedPoint.Length - 1);
            ECPoint R = ecParams.Curve.DecodePoint(compressedPoint);

            Console.WriteLine("R: " + ToHex(R.GetEncoded()));

            if (check)
            {
                ECPoint O = R.Multiply(order);
                if (!O.IsInfinity)
                {
                    throw new Exception("Check failed");
                }
            }

            int        n = (ecParams.Curve as FpCurve).Q.ToByteArrayUnsigned().Length *8;
            BigInteger e = new BigInteger(1, hash);

            if (8 * hash.Length > n)
            {
                e = e.ShiftRight(8 - (n & 7));
            }
            e = BigInteger.Zero.Subtract(e).Mod(order);
            BigInteger rr  = sig[0].ModInverse(order);
            BigInteger sor = sig[1].Multiply(rr).Mod(order);
            BigInteger eor = e.Multiply(rr).Mod(order);
            ECPoint    Q   = ecParams.G.Multiply(eor).Add(R.Multiply(sor));

            Console.WriteLine("n: " + n);
            Console.WriteLine("e: " + ToHex(e.ToByteArrayUnsigned()));
            Console.WriteLine("rr: " + ToHex(rr.ToByteArrayUnsigned()));
            Console.WriteLine("sor: " + ToHex(sor.ToByteArrayUnsigned()));
            Console.WriteLine("eor: " + ToHex(eor.ToByteArrayUnsigned()));
            Console.WriteLine("Q: " + ToHex(Q.GetEncoded()));

            return(Q);
        }
Example #26
0
        public static Signature Sign(Hash32 hash, PrivateKey privateKey)
        {
            BigInteger pk = new BigInteger(1, privateKey.Binary.ToArray());

            X9ECParameters         ec           = SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters     domainParams = new ECDomainParameters(ec.Curve, ec.G, ec.N, ec.H);
            ECPrivateKeyParameters param        = new ECPrivateKeyParameters(pk, domainParams);
            ECDsaSigner            signer       = new ECDsaSigner(new HMacDsaKCalculator(new Sha256Digest()));

            signer.Init(true, param);

            var hashArray = hash.Binary.ToArray();

            BigInteger[] sig = signer.GenerateSignature(hashArray);

            BigInteger r = sig[0];
            BigInteger s = sig[1];

            if (s.CompareTo(domainParams.N.ShiftRight(1)) > 0)
            {
                s = domainParams.N.Subtract(s);
            }

            ECPoint q            = domainParams.G.Multiply(pk);
            var     publicParams = new ECPublicKeyParameters(q, domainParams);

            byte[] publicBytes = publicParams.Q.GetEncoded();

            int recid = -1;

            for (int rec = 0; rec < 4; rec++)
            {
                try
                {
                    ECPoint Q = Recover(sig, hashArray, rec, true);
                    if (Enumerable.SequenceEqual(publicBytes, Q.GetEncoded()))
                    {
                        recid = rec;
                        break;
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
            if (recid < 0)
            {
                throw new Exception("Did not find proper recid");
            }

            byte[] fullSigBytes = new byte[65];
            Buffer.BlockCopy(sig[0].ToByteArrayUnsigned(), 0, fullSigBytes, 0, 32);
            Buffer.BlockCopy(sig[1].ToByteArrayUnsigned(), 0, fullSigBytes, 32, 32);
            fullSigBytes[64] = (byte)recid;

            return(new Signature(fullSigBytes));
        }
Example #27
0
    public string GetSign(byte[] msg)
    {
        //Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math.BigInteger(Convert.FromBase64String(privKey));
        byte[] prvB = StringToByteArray(prv);
        byte[] pubB = StringToByteArray(pub);
        //byte[] prvB = StringToByteArray(prvTmp);
        //byte[] pubB = StringToByteArray(pubTmp);
        Org.BouncyCastle.Math.BigInteger sk = new Org.BouncyCastle.Math.BigInteger(+1, prvB);
        Org.BouncyCastle.Math.EC.ECPoint q  = domain.G.Multiply(sk);

        byte[]     pubKeyX = q.Normalize().AffineXCoord.GetEncoded();
        byte[]     pubKeyY = q.Normalize().AffineYCoord.GetEncoded();
        BigInteger k       = GenerateRandom();

        //BigInteger k = new BigInteger(+1,StringToByteArray("015B931D9C7BF3A7A70E57868BF29712377E74355FC59032CD7547C80E179010"));
        //Debug.Log("kv:" + BitConverter.ToString(kv.ToByteArray()).Replace("-", ""));
        Debug.Log("K:" + BitConverter.ToString(k.ToByteArray()).Replace("-", ""));
        ECPoint Q = domain.G.Multiply(k);

        Org.BouncyCastle.Crypto.Digests.Sha256Digest digester = new Org.BouncyCastle.Crypto.Digests.Sha256Digest();
        byte[] h = new byte[digester.GetDigestSize()];

        digester.BlockUpdate(Q.GetEncoded(true), 0, Q.GetEncoded(true).Length);
        digester.BlockUpdate(pubB, 0, pubB.Length);
        digester.BlockUpdate(msg, 0, msg.Length);

        digester.DoFinal(h, 0);

        Org.BouncyCastle.Math.BigInteger r = new Org.BouncyCastle.Math.BigInteger(+1, h);

        BigInteger s = r.Multiply(sk);

        s = k.Subtract(s);
        s = s.Mod(domain.n);
        string rt = BitConverter.ToString(r.ToByteArray()).Replace("-", "");

        if (rt.Length > 32)
        {
            rt = rt.Remove(0, 2);
        }
        string st = BitConverter.ToString(s.ToByteArray()).Replace("-", "");

        return(rt + st);
    }
Example #28
0
 public PublicKey(ECPoint point)
 {
     this.IsCompressedPoint = point.IsCompressed;
     this.point             = point;
     this.PublicKeyBytes    = point.GetEncoded();
     if (validatePoint() == false)
     {
         throw new ArgumentException("Not a valid public key");
     }
 }
Example #29
0
        internal static byte[] GetStealthSharedSecret(Key priv, PubKey pub)
        {
            X9ECParameters curve = ECKey.Secp256k1;
            ECPoint        pubec = curve.Curve.DecodePoint(pub.ToBytes());
            ECPoint        p     = pubec.Multiply(new BigInteger(1, priv.ToBytes()));

            byte[] pBytes = new PubKey(p.GetEncoded()).Compress().ToBytes();
            byte[] hash   = Hashes.SHA256(pBytes);
            return(hash);
        }
Example #30
0
        public PubKey Uncover(Key priv, PubKey pub)
        {
            X9ECParameters curve = ECKey.Secp256k1;

            byte[] hash = GetStealthSharedSecret(priv, pub);
            //Q' = Q + cG
            ECPoint qprim = curve.G.Multiply(new BigInteger(1, hash)).Add(curve.Curve.DecodePoint(ToBytes()));

            return(new PubKey(qprim.GetEncoded()).Compress(this.IsCompressed));
        }