/// <summary>
        /// Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again. This is
        /// standard procedure in BitCoin. The resulting hash is in big endian form.
        /// </summary>
        public static byte[] DoubleDigest(byte[] input, int offset, int length)
        {
            var algorithm = new Sha256Digest();

            Byte[] firstHash = new Byte[algorithm.GetDigestSize()];
            algorithm.BlockUpdate(input, offset, length);
            algorithm.DoFinal(firstHash, 0);
            Byte[] secondHash = new Byte[algorithm.GetDigestSize()];
            algorithm.BlockUpdate(firstHash, 0, firstHash.Length);
            algorithm.DoFinal(secondHash, 0);
            return(secondHash);
        }
        /// <summary>
        /// Calculates SHA256(SHA256(byte range 1 + byte range 2)).
        /// </summary>
        public static byte[] DoubleDigestTwoBuffers(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2)
        {
            var algorithm = new Sha256Digest();
            var buffer    = new byte[length1 + length2];

            Array.Copy(input1, offset1, buffer, 0, length1);
            Array.Copy(input2, offset2, buffer, length1, length2);
            Byte[] first = new Byte[algorithm.GetDigestSize()];
            algorithm.DoFinal(first, 0);
            algorithm.BlockUpdate(first, 0, first.Length);
            Byte[] output = new Byte[algorithm.GetDigestSize()];
            algorithm.DoFinal(output, 0);
            return(output);
        }
Пример #3
0
        /// <summary>
        /// Creates a signature from the given <paramref name="message"/>.
        /// <para>
        /// A created signature can be verified by the corresponding
        /// <see cref="PublicKey"/>.
        /// </para>
        /// <para>
        /// Signatures can be created by only the <see cref="PrivateKey"/>
        /// which corresponds a <see cref="PublicKey"/> to verify these
        /// signatures.
        /// </para>
        /// <para>
        /// To sum up, a signature is used to guarantee:
        /// </para>
        /// <list type="bullet">
        /// <item><description>that the <paramref name="message"/> was created
        /// by someone possessing the corresponding <see cref="PrivateKey"/>,
        /// </description></item>
        /// <item><description>that the possessor cannot deny having sent the
        /// <paramref name="message"/>, and</description></item>
        /// <item><description>that the <paramref name="message"/> was not
        /// forged in the middle of transit.</description></item>
        /// </list>
        /// </summary>
        /// <param name="message">A message to sign in <see cref="byte"/> array
        /// representation.</param>
        /// <returns>A signature that verifies the <paramref name="message"/>.
        /// It can be verified using
        /// <see cref="Libplanet.Crypto.PublicKey.Verify(byte[], byte[])"/>
        /// method.</returns>
        /// <seealso cref="Libplanet.Crypto.PublicKey.Verify(byte[], byte[])"/>
        public byte[] Sign(byte[] message)
        {
            var h      = new Sha256Digest();
            var hashed = new byte[h.GetDigestSize()];

            h.BlockUpdate(message, 0, message.Length);
            h.DoFinal(hashed, 0);
            h.Reset();

            var kCalculator = new HMacDsaKCalculator(h);
            var signer      = new ECDsaSigner(kCalculator);

            signer.Init(true, keyParam);
            BigInteger[] rs = signer.GenerateSignature(hashed);
            var          r  = rs[0];
            var          s  = rs[1];

            BigInteger otherS = keyParam.Parameters.N.Subtract(s);

            if (s.CompareTo(otherS) == 1)
            {
                s = otherS;
            }

            var bos = new MemoryStream(72);
            var seq = new DerSequenceGenerator(bos);

            seq.AddObject(new DerInteger(r));
            seq.AddObject(new DerInteger(s));
            seq.Close();
            return(bos.ToArray());
        }
Пример #4
0
        public byte[] GetHash(Version version)
        {
            if (version == null)
            {
                throw new ArgumentNullException(nameof(version));
            }

            byte[] handshakeHash;
            if (version < DTLSRecord.Version1_2)
            {
                IDigest sha1 = new Sha1Digest(this._VerifyHandshakeSHA1);
                IDigest md5  = new MD5Digest(this._VerifyHandshakeMD5);
                handshakeHash = new byte[sha1.GetDigestSize() + md5.GetDigestSize()];
                md5.DoFinal(handshakeHash, 0);
                sha1.DoFinal(handshakeHash, md5.GetDigestSize());
            }
            else
            {
                IDigest hash = new Sha256Digest((Sha256Digest)this._VerifyHandshake);
                handshakeHash = new byte[hash.GetDigestSize()];
                hash.DoFinal(handshakeHash, 0);
            }

            return(handshakeHash);
        }
Пример #5
0
        private static Boolean SignatureMatches(string encodedSignature, string encodedAgreement, string signTextTransformation, OpensignSignature opensignSignature)
        {
            if (!encodedAgreement.Equals(encodedSignature))
            {
                return(false);
            }

            var stylesheetDigest = opensignSignature.StylesheetDigest;

            if (stylesheetDigest != null)
            {
                if (signTextTransformation == null)
                {
                    throw new ArgumentException("signTextTransformation is required for XML signing");
                }

                var    digest          = new Sha256Digest();
                var    encode          = new ASCIIEncoding();
                byte[] stylesheetBytes = encode.GetBytes(signTextTransformation);
                digest.BlockUpdate(stylesheetBytes, 0, stylesheetBytes.Length);
                var digestBytes = new byte[digest.GetDigestSize()];
                digest.DoFinal(digestBytes, 0);
                var calculatedDigest = Encoding.UTF8.GetString(digestBytes, 0, digestBytes.Length);

                return(stylesheetDigest.Equals(calculatedDigest));
            }
            return(true);
        }
Пример #6
0
        private void buttonSignTest_Click(object sender, EventArgs e)
        {
            // perpare simple hash value to sign
            byte[] DataToSign = Encoding.UTF8.GetBytes("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.");
            var    hashAlgo   = new Sha256Digest();

            hashAlgo.BlockUpdate(DataToSign, 0, DataToSign.Length);
            byte[] hashToSign = new byte[hashAlgo.GetDigestSize()];
            hashAlgo.DoFinal(hashToSign, 0);


            var c = InitClient();

            if (null == c)
            {
                return;
            }

            var signature = c.Sign(hashToSign);

            if (null == signature)
            {
                WriteText("seal sign failed");
            }
            else
            {
                WriteText("signature: " + Convert.ToBase64String(signature));
            }

            if (null != seal_cert)
            {
                VerifySignature(DataToSign, signature);
            }
        }
Пример #7
0
        public static bool DoVerifyEcDsaSha256P256_old(IEnumerable <BufLen> bufs, I2PSigningPublicKey key, I2PSignature signed)
        {
            if (!SupportedSignatureType(signed.Certificate.SignatureType))
            {
                throw new NotImplementedException();
            }

            var sha = new Sha256Digest();

            foreach (var buf in bufs)
            {
                sha.BlockUpdate(buf.BaseArray, buf.BaseArrayOffset, buf.Length);
            }
            var hash = new byte[sha.GetDigestSize()];

            sha.DoFinal(hash, 0);

            var p     = Org.BouncyCastle.Asn1.Nist.NistNamedCurves.GetByName("P-256");
            var param = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            var pk    = new ECPublicKeyParameters(p.Curve.DecodePoint(key.ToByteArray()), param);

            var dsa = new Org.BouncyCastle.Crypto.Signers.DsaSigner();

            var sigsize = signed.Certificate.SignatureLength;
            var r       = new BigInteger(1, signed.Sig.BaseArray, signed.Sig.BaseArrayOffset + 0, sigsize / 2);
            var s       = new BigInteger(1, signed.Sig.BaseArray, signed.Sig.BaseArrayOffset + sigsize / 2, sigsize / 2);

            dsa.Init(false, pk);
            var result = dsa.VerifySignature(hash, r, s);

            DebugUtils.LogDebug("DoVerifyEcDsaSha256P256: " + result.ToString());
            return(result);
        }
Пример #8
0
        private BigInteger SMPHash(byte hash_number, BigInteger big_int_a, BigInteger big_int_b)
        {
            byte[] _encoded_mpi = null;



            Sha256Digest _sha256 = new Sha256Digest();


            _sha256.Update(hash_number);

            Utility.EncodeMpiBytes(big_int_a, ref _encoded_mpi);
            _sha256.BlockUpdate(_encoded_mpi, 0, _encoded_mpi.Length);


            if (big_int_b != null)
            {
                Utility.EncodeMpiBytes(big_int_b, ref _encoded_mpi);
                _sha256.BlockUpdate(_encoded_mpi, 0, _encoded_mpi.Length);
            }



            byte[] _hashed_bytes = new byte[_sha256.GetDigestSize()];

            _sha256.DoFinal(_hashed_bytes, 0);



            return(new BigInteger(1, _hashed_bytes));
        }
Пример #9
0
        /// Takes the given [data], converts it to an alphabetically sorted
        /// JSON object and signs its content using the given [wallet].
        public static byte[] signSorted(Object data, Wallet wallet)
        {
            //Dictionary<String, Object> sorted = null;
            //if (data is Dictionary<String, Object>)
            //{
            //    sorted = MapSorter.sort((Dictionary<String, Object>)data);
            //}
            //String jsonData = JsonConvert.SerializeObject(sorted);

            // Encode the sorted JSON to a string
            String jsonData = JsonConvert.SerializeObject(data);

            byte[] utf8Bytes = Encoding.UTF8.GetBytes(jsonData);
            //// *** Create a Sha256 of the message - Method Microsoft
            // SHA256 sha256Hash = SHA256.Create();
            // byte[] hashBytes = sha256Hash.ComputeHash(utf8Bytes);
            // *** Create a Sha256 of the message - Method BouncyCastle
            Sha256Digest sha256 = new Sha256Digest();

            sha256.BlockUpdate(utf8Bytes, 0, utf8Bytes.Length);
            byte[] hashBytes = new byte[sha256.GetDigestSize()];
            sha256.DoFinal(hashBytes, 0);

            // Sign and return the message
            return(wallet.sign(hashBytes));
        }
Пример #10
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));
        }
Пример #11
0
        /// <summary>
        /// Computes the signature for an arbitrary message based on two private scalars:
        /// The one-time signing key and the oracle's private key
        /// </summary>
        /// <param name="privateKey">The private key to sign with</param>
        /// <param name="oneTimeSigningKey">The one-time signing key to sign with</param>
        /// <param name="message">The message to sign</param>
        public static byte[] ComputeSignature(byte[] privKey, byte[] oneTimeSigningKey, byte[] message)
        {
            BigInteger bigPriv = BigIntegerFromBytes(privKey);
            BigInteger bigK    = BigIntegerFromBytes(oneTimeSigningKey);

            ECPoint r = domain.G.Multiply(bigK).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);

            BigInteger bigS = bigE.Multiply(bigPriv);

            var bigS2 = bigK.Subtract(bigS);
            var bigS3 = bigS2.Mod(curve.N);

            byte[] sigBytes  = StringToByteArray(BigIntegerToString(bigS3));
            byte[] signature = new byte[32];
            Array.Copy(sigBytes, 0, signature, 32 - sigBytes.Length, sigBytes.Length);
            return(signature);
        }
 private static byte[] GetDigestInByteArray(
     FileInfo file,
     CancellationToken cancellationToken)
 {
     using (var readStream = file.OpenRead())
     {
         var digest = new Sha256Digest();
         var output = new byte[digest.GetDigestSize()];
         var buffer = new byte[BufferSizeInByte];
         int read;
         while ((read = readStream.Read(
                     buffer,
                     0,
                     buffer.Length)) > 0)
         {
             cancellationToken.ThrowIfCancellationRequested();
             digest.BlockUpdate(
                 buffer,
                 0,
                 read
                 );
         }
         digest.DoFinal(
             output,
             0
             );
         return(output);
     }
 }
Пример #13
0
 public byte[] CalculateSha256Hash(byte[] value)
 {
     var digest = new Sha256Digest();
     var output = new byte[digest.GetDigestSize()];
     digest.BlockUpdate(value, 0, value.Length);
     digest.DoFinal(output, 0);
     return output;
 }
Пример #14
0
        /**
         * Hashes the given data.
         *
         * @param data The data to hash
         * @return byte-array containing the hashed data
         */
        public static byte[] Hash(byte[] data)
        {
            Sha256Digest sha256 = new Sha256Digest();

            sha256.BlockUpdate(data, 0, data.Length);
            byte[] hash = new byte[sha256.GetDigestSize()];
            sha256.DoFinal(hash, 0);
            return(hash);
        }
Пример #15
0
    public static byte[] Hash256(byte[] src)
    {
        Sha256Digest sha = new Sha256Digest();

        sha.BlockUpdate(src, 0, src.Length);
        byte[] output = new byte[sha.GetDigestSize()];
        sha.DoFinal(output, 0);
        return(output);
    }
Пример #16
0
        public static byte[] ComputeSha256(byte[] data)
        {
            IDigest digest = new Sha256Digest();

            byte[] buffer = new byte[digest.GetDigestSize()];
            digest.BlockUpdate(data, 0, data.Length);
            digest.DoFinal(buffer, 0);
            return(buffer);
        }
Пример #17
0
    public static byte[] Sha256Process(byte[] input, int offset, int length)
    {
        var algorithm = new Sha256Digest();

        Byte[] firstHash = new Byte[algorithm.GetDigestSize()];
        algorithm.BlockUpdate(input, offset, length);
        algorithm.DoFinal(firstHash, 0);
        return(firstHash);
    }
Пример #18
0
        private byte[] BouncyCastle(byte[] data)
        {
            byte[] digest = new byte[bouncyCastle.GetDigestSize()];

            bouncyCastle.BlockUpdate(data, 0, data.Length);
            bouncyCastle.DoFinal(digest, 0);

            return(digest);
        }
Пример #19
0
        public uint256 GetHash()
        {
            var blake2b = new Sha256Digest();
            var hash1   = new byte[blake2b.GetDigestSize()];
            var hash2   = new byte[blake2b.GetDigestSize()];

            var buffer = ((MemoryStream)Inner).ToArrayEfficient();
            var h      = NBitcoin.Crypto.SCrypt.ComputeDerivedKey(buffer, buffer, 1024, 1, 1, null, 32);

            return(new uint256(h));

            //blake2b.BlockUpdate(((MemoryStream)Inner).ToArrayEfficient(), 0, (int)Inner.Length);
            //blake2b.DoFinal(hash1, 0);
            //blake2b.BlockUpdate(hash1, 0, (int)hash1.Length);
            //blake2b.DoFinal(hash2, 0);

            return(new uint256(hash2));
        }
Пример #20
0
        public byte[] hashData(byte[] data)
        {
            IDigest digest = new Sha256Digest();
            var     resBuf = new byte[digest.GetDigestSize()];

            digest.BlockUpdate(data, 0, data.Length);
            digest.DoFinal(resBuf, 0);
            return(resBuf);
        }
Пример #21
0
        public static byte[] Sha3(byte[] bytes)
        {
            Sha256Digest digest = new Sha256Digest();

            digest.BlockUpdate(bytes, 0, bytes.Length);
            byte[] result = new byte[digest.GetDigestSize()];
            digest.DoFinal(result, 0);
            return(result);
        }
Пример #22
0
        public static byte[] GetSha256Hash(byte[] buffer)
        {
            Sha256Digest sha256Digest = new Sha256Digest();

            sha256Digest.BlockUpdate(buffer, 0, buffer.Length);
            byte[] hash = new byte[sha256Digest.GetDigestSize()];
            sha256Digest.DoFinal(hash, 0);
            return(hash);
        }
Пример #23
0
        private byte[] CalculateInputValidation(byte[] inputValidation)
        {
            var hash = new Sha256Digest();

            hash.BlockUpdate(inputValidation, 0, inputValidation.Length);
            byte[] result = new byte[hash.GetDigestSize()];
            hash.DoFinal(result, 0);
            return(result);
        }
Пример #24
0
        private static byte[] sha256Hash(byte[] message)
        {
            Sha256Digest sha256Digest = new Sha256Digest();

            sha256Digest.BlockUpdate(message, 0, message.Length);
            byte[] hash = new byte[sha256Digest.GetDigestSize()];
            sha256Digest.DoFinal(hash, 0);
            return(hash);
        }
Пример #25
0
        static byte[] Sha256(byte[] dat)
        {
            Sha256Digest digester = new Sha256Digest();

            byte[] retValue = new byte[digester.GetDigestSize()];
            digester.BlockUpdate(dat, 0, dat.Length);
            digester.DoFinal(retValue, 0);
            return(retValue);
        }
Пример #26
0
        public static byte[] ComputeSha256Hash(byte[] data)
        {
            var shaHash = new Sha256Digest();

            shaHash.BlockUpdate(data, 0, data.Length);
            byte[] hashedValue = new byte[shaHash.GetDigestSize()];
            shaHash.DoFinal(hashedValue, 0);
            return(hashedValue);
        }
Пример #27
0
        internal static byte[] ComputeSHA256Hash(byte[] msg)
        {
            var hash = new Sha256Digest();

            hash.BlockUpdate(msg, 0, msg.Length);
            byte[] result = new byte[hash.GetDigestSize()];
            hash.DoFinal(result, 0);
            return(result);
        }
Пример #28
0
        /// <summary>
        /// provides a SHA256 hash of the the inputbytes
        /// </summary>
        public static byte[] Sha256(byte[] inputBytes)
        {
            Sha256Digest sha256 = new Sha256Digest();

            sha256.BlockUpdate(inputBytes, 0, inputBytes.Length);
            byte[] hash = new byte[sha256.GetDigestSize()];
            sha256.DoFinal(hash, 0);
            return(hash);
        }
Пример #29
0
        public byte[] ComputeHash(byte[] data)
        {
            Sha256Digest sha256 = new Sha256Digest();

            sha256.BlockUpdate(data, 0, data.Length);
            byte[] result = new byte[sha256.GetDigestSize()];
            sha256.DoFinal(result, 0);
            return(result);
        }
Пример #30
0
        /// <summary>
        /// Sha256 hash
        /// </summary>
        static public byte[] Sha256Hash(byte[] data)
        {
            Sha256Digest digest = new Sha256Digest();

            digest.BlockUpdate(data, 0, data.Length);
            byte[] hash = new byte[digest.GetDigestSize()];
            digest.DoFinal(hash, 0);
            return(hash);
        }