Esempio n. 1
0
        public ECPoint RecoverFromSignature(byte[] hash, BigInteger r, BigInteger s, int recId)
        {
            var x = r;

            if (recId > 1 && recId < 4)
            {
                x += Secp256k1.N;
                x  = x % Secp256k1.P;
            }

            if (x >= Secp256k1.P)
            {
                return(null);
            }

            byte[] xBytes          = x.ToByteArrayUnsigned(true);
            byte[] compressedPoint = new Byte[33];
            compressedPoint[0] = (byte)(0x02 + (recId % 2));
            Buffer.BlockCopy(xBytes, 0, compressedPoint, 33 - xBytes.Length, xBytes.Length);

            ECPoint publicKey = ECPoint.DecodePoint(compressedPoint);

            if (!publicKey.Multiply(Secp256k1.N).IsInfinity)
            {
                return(null);
            }

            var z = -hash.ToBigIntegerUnsigned(true) % Secp256k1.N;

            if (z < 0)
            {
                z += Secp256k1.N;
            }

            var rr = r.ModInverse(Secp256k1.N);
            var u1 = (z * rr) % Secp256k1.N;
            var u2 = (s * rr) % Secp256k1.N;

            var Q = Secp256k1.G.Multiply(u1).Add(publicKey.Multiply(u2)).Normalize();

            return(Q);
        }
Esempio n. 2
0
        public byte[] Decrypt(BigInteger privateKey, byte[] cipherData)
        {
            byte[] tagBytes = new byte[65];
            Buffer.BlockCopy(cipherData, 0, tagBytes, 0, tagBytes.Length);
            var keyPoint = ECPoint.DecodePoint(tagBytes);

            byte[] iv = new byte[16];
            Buffer.BlockCopy(cipherData, 65, iv, 0, iv.Length);

            byte[] cipher = new byte[cipherData.Length - 16 - 65];
            Buffer.BlockCopy(cipherData, 65 + 16, cipher, 0, cipher.Length);

            byte[] key = ecElGamal.DecipherKey(privateKey, keyPoint);

            aesEncryption.IV  = iv;
            aesEncryption.Key = key;

            ICryptoTransform decryptor = aesEncryption.CreateDecryptor();

            byte[] decryptedData = decryptor.TransformFinalBlock(cipher, 0, cipher.Length);

            return(decryptedData);
        }