Beispiel #1
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));
        }
Beispiel #2
0
        private static byte[] Base58CheckToByteArray(string address)
        {
            var bytes = AddressToByteArray(address);

            if (bytes == null || bytes.Length < 4)
            {
                return(null);
            }

            var adjustedLength = bytes.Length - 4;
            var checksum       = new byte[32];

            var sha256 = new Sha256Digest();

            sha256.BlockUpdate(bytes, 0, adjustedLength);
            sha256.DoFinal(checksum, 0);
            sha256.BlockUpdate(checksum, 0, 32);
            sha256.DoFinal(checksum, 0);

            for (var i = 0; i < 4; i++)
            {
                if (checksum[i] != bytes[adjustedLength + i])
                {
                    return(null);
                }
            }
            return(bytes);
        }
Beispiel #3
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);
        }
Beispiel #4
0
            private void BuildFromSeed(byte[] seed)
            {
                if (seed.Length != M)
                {
                    throw new CoseException("Incorrect seed length");
                }

                int keyCount = 1 << H;
                int p        = Constants.Values[(int)_lmotsType].p;

                _x = new byte[keyCount][];
                //  Build LMS Private Key
                for (int q = 0; q < keyCount; q++)
                {
                    byte[] qBytes = u32str(q);
                    //  Build LM-OTS private key for each leaf
                    _x[q] = new byte[M * p];
                    for (UInt16 j = 0; j < p; j++)
                    {
                        Sha256Digest h = new Sha256Digest();
                        h.BlockUpdate(Identifier, 0, Identifier.Length);
                        h.BlockUpdate(qBytes, 0, qBytes.Length);
                        h.BlockUpdate(u16str(j), 0, 2);
                        h.Update(0xff);
                        h.BlockUpdate(seed, 0, seed.Length);
                        h.DoFinal(_x[q], j * M);
                    }
                }

                // Derive the public key

                ComputePublicKey();
            }
Beispiel #5
0
        public static string GetAddressForContract(Transaction.Transaction tx)
        {
            string senderAddress = KeyTools.GetAddressFromPublicKey(tx.SenderPubKey);

            SHA256Managed.Create().ComputeHash(ByteUtil.HexStringToByteArray(senderAddress));
            Sha256Digest sha = new Sha256Digest();

            byte[] senderAddressBytes = ByteUtil.HexStringToByteArray(senderAddress);
            sha.BlockUpdate(senderAddressBytes, 0, senderAddressBytes.Count());

            int nonce = 0;

            if (!string.IsNullOrEmpty(tx.Nonce))
            {
                nonce = int.Parse(tx.Nonce);
                nonce--;
            }
            string hexNonce = Validation.IntToHex(nonce, 16);

            byte[] hexNonceBytes = ByteUtil.HexStringToByteArray(hexNonce);
            sha.BlockUpdate(hexNonceBytes, 0, hexNonceBytes.Count());
            byte[] bytes = new byte[sha.GetByteLength()];
            sha.DoFinal(bytes, 0);

            return(ByteUtil.ByteArrayToHexString(bytes).Substring(24, 40));
        }
Beispiel #6
0
        private static byte[] Base58CheckToByteArray(string base58)
        {
            byte[] bb = Base58.ToByteArray(base58);
            if (bb == null || bb.Length < 4)
            {
                return(null);
            }

            Sha256Digest bcsha256a = new Sha256Digest();

            bcsha256a.BlockUpdate(bb, 0, bb.Length - 4);

            byte[] checksum = new byte[32];
            bcsha256a.DoFinal(checksum, 0);
            bcsha256a.BlockUpdate(checksum, 0, 32);
            bcsha256a.DoFinal(checksum, 0);

            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);
        }
Beispiel #7
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));
        }
Beispiel #8
0
        /// <summary>
        /// Calculate the SHA256-Hash of the share
        /// </summary>
        public byte[] GetHash()
        {
            Sha256Digest sha256 = new Sha256Digest();

            byte[] hash = new byte[sha256.GetByteLength()];
            sha256.BlockUpdate(X, 0, X.Length);
            sha256.BlockUpdate(Y, 0, Y.Length);
            sha256.GetByteLength();
            sha256.DoFinal(hash, 0);
            return(hash);
        }
Beispiel #9
0
        public static byte[] SHA256_SHA256(byte[] ba)
        {
            Sha256Digest bcsha256a = new Sha256Digest();

            bcsha256a.BlockUpdate(ba, 0, ba.Length);
            byte[] thehash = new byte[32];
            bcsha256a.DoFinal(thehash, 0);
            bcsha256a.BlockUpdate(thehash, 0, 32);
            bcsha256a.DoFinal(thehash, 0);
            return(thehash);
        }
        public static byte[] ComputeDoubleSha256(byte[] ofwhat)
        {
            Sha256Digest sha256 = new Sha256Digest();

            sha256.BlockUpdate(ofwhat, 0, ofwhat.Length);
            byte[] rv = new byte[32];
            sha256.DoFinal(rv, 0);
            sha256.BlockUpdate(rv, 0, rv.Length);
            sha256.DoFinal(rv, 0);
            return(rv);
        }
Beispiel #11
0
        public static uint256 Hash256(byte[] data, int offset, int count)
        {
            var sha256 = new Sha256Digest();

            sha256.BlockUpdate(data, offset, count);
            var rv = new byte[32];

            sha256.DoFinal(rv, 0);
            sha256.BlockUpdate(rv, 0, rv.Length);
            sha256.DoFinal(rv, 0);
            return(new uint256(rv));
        }
        /// <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);
        }
Beispiel #13
0
        /// <summary>
        /// From a single given key create a hashname with the intermediate hashes of other keys
        /// </summary>
        /// <returns>The key.</returns>
        /// <param name="csid">The identifier for the cipher set as a string.</param>
        /// <param name="keyData">The key data for the given csid.</param>
        /// <param name="intermediates">Intermediates.</param>
        public static string FromKey(string csid, byte[] keyData, IDictionary <string, string> intermediates)
        {
            Sha256Digest  digest = new Sha256Digest();
            List <string> keys   = new List <string>(intermediates.Keys);

            keys.Add(csid);
            keys.Sort();

            int digestSize = digest.GetDigestSize();

            byte[] outhash = null;
            foreach (var key in keys)
            {
                if (outhash != null)
                {
                    digest.BlockUpdate(outhash, 0, digestSize);
                }
                else
                {
                    outhash = new byte[digestSize];
                }
                byte inByte;
                try {
                    inByte = Convert.ToByte(key, 16);
                } catch (FormatException) {
                    return(null);
                } catch (OverflowException) {
                    return(null);
                } catch (ArgumentException) {
                    return(null);
                }
                digest.Update(inByte);
                digest.DoFinal(outhash, 0);
                digest.Reset();

                digest.BlockUpdate(outhash, 0, digestSize);
                if (key == csid)
                {
                    Sha256Digest keyDigest = new Sha256Digest();
                    keyDigest.BlockUpdate(keyData, 0, keyData.Length);
                    keyDigest.DoFinal(outhash, 0);
                    digest.BlockUpdate(outhash, 0, outhash.Length);
                }
                else
                {
                    byte[] keyIntermediate = Base32Encoder.Decode(intermediates [key]);
                    digest.BlockUpdate(keyIntermediate, 0, keyIntermediate.Length);
                }
                digest.DoFinal(outhash, 0);
            }
            return(Base32Encoder.Encode(outhash).TrimEnd(trimChars).ToLower());
        }
Beispiel #14
0
        public static byte[] ToSHA256(this byte[] bytes)
        {
            bytes.ThrowIfNull("bytes");

            var sha  = new Sha256Digest();
            var hash = new byte[32];

            sha.BlockUpdate(bytes, 0, bytes.Length);
            sha.DoFinal(hash, 0);
            sha.BlockUpdate(hash, 0, 32);
            sha.DoFinal(hash, 0);

            return(hash);
        }
Beispiel #15
0
        public static string FromKeys(IDictionary <string, string> publicKeys)
        {
            // You've gotta have some keys to hash!
            if (publicKeys.Count <= 0)
            {
                return(null);
            }
            Sha256Digest  digest = new Sha256Digest();
            List <string> keys   = new List <string>(publicKeys.Keys);

            keys.Sort();

            int digestSize = digest.GetDigestSize();

            byte[] outhash = null;
            foreach (var key in keys)
            {
                if (outhash != null)
                {
                    digest.BlockUpdate(outhash, 0, digestSize);
                }
                else
                {
                    outhash = new byte[digestSize];
                }
                byte inByte;
                try {
                    inByte = Convert.ToByte(key, 16);
                } catch (FormatException) {
                    return(null);
                } catch (OverflowException) {
                    return(null);
                } catch (ArgumentException) {
                    return(null);
                }
                digest.Update(inByte);
                digest.DoFinal(outhash, 0);
                digest.Reset();

                digest.BlockUpdate(outhash, 0, digestSize);
                byte[]       keyData   = Base32Encoder.Decode(publicKeys [key]);
                Sha256Digest keyDigest = new Sha256Digest();
                keyDigest.BlockUpdate(keyData, 0, keyData.Length);
                keyDigest.DoFinal(outhash, 0);
                digest.BlockUpdate(outhash, 0, outhash.Length);
                digest.DoFinal(outhash, 0);
            }
            return(Base32Encoder.Encode(outhash).TrimEnd(trimChars).ToLower());
        }
        private void calcPubKeyHash()
        {
            X509Certificate  x509 = this.Get509Certificate();
            RsaKeyParameters key  = x509.GetPublicKey() as RsaKeyParameters;

            byte[]  exp  = key.Exponent.ToByteArrayUnsigned();
            byte[]  mod  = key.Modulus.ToByteArrayUnsigned();
            IDigest hash = new Sha256Digest();

            CkaSubPubKeyHash = new byte[hash.GetDigestSize()];

            hash.BlockUpdate(exp, 0, exp.Length);
            hash.BlockUpdate(mod, 0, mod.Length);
            hash.DoFinal(CkaSubPubKeyHash, 0);
        }
        private void GetSymmetricKey()
        {
            var infoToWrite = GetInfoReady(this.merchantIdentifierField);

            IDigest digest = new Sha256Digest();

            this.symmetricKey = new byte[digest.GetDigestSize()];
            digest.Update((byte)(1 >> 24));
            digest.Update((byte)(1 >> 16));
            digest.Update((byte)(1 >> 8));
            digest.Update((byte)1);
            digest.BlockUpdate(this.sharedSecret, 0, this.sharedSecret.Length);
            digest.BlockUpdate(infoToWrite, 0, infoToWrite.Length);
            digest.DoFinal(this.symmetricKey, 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));
        }
Beispiel #19
0
        /// <summary>
        /// Generate a signature
        /// Using https://github.com/Zaliro/Switcheo.Net/blob/master/Switcheo.Net/SwitcheoAuthenticationProvider.cs
        /// </summary>
        /// <param name="message">Message to sign</param>
        /// <param name="wallet">Wallet for signature</param>
        /// <returns>Message signature</returns>
        private string GenerateSignature(byte[] message, NeoWallet wallet)
        {
            var privateKey = wallet.privateKey;

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

            var priv     = new ECPrivateKeyParameters("ECDSA", (new BigInteger(1, privateKey)), domain);
            var signer   = new ECDsaSigner();
            var fullsign = new byte[64];

            var hash = new Sha256Digest();

            hash.BlockUpdate(message, 0, message.Length);

            var result = new byte[32];

            hash.DoFinal(result, 0);

            message = result;

            signer.Init(true, priv);
            var signature = signer.GenerateSignature(message);

            var signedResult = ProcessSignature(signature);

            var signedMessage = BitConverter.ToString(signedResult);

            return(signedMessage.Replace("-", "").ToLower());
        }
 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);
     }
 }
Beispiel #21
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);
            }
        }
Beispiel #22
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);
        }
Beispiel #23
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);
        }
Beispiel #24
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());
        }
Beispiel #25
0
        private uint256 FastSHA256(byte[] data, int offset, int count)
        {
            Sha256Digest sha256 = new Sha256Digest();

            sha256.BlockUpdate(data, offset, count);
            return(new uint256(sha256.MidState));
        }
Beispiel #26
0
 public void Process(ArraySegment <byte> data)
 {
     if (_sha == null)
     {
         throw new ObjectDisposedException(nameof(Digest));
     }
     _sha.BlockUpdate(data.Array, data.Offset, data.Count);
 }
Beispiel #27
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;
 }
        public static string ByteArrayToBase58Check(byte[] ba)
        {
            byte[] bb = new byte[ba.Length + 4];
            Array.Copy(ba, bb, ba.Length);
            Sha256Digest bcsha256a = new Sha256Digest();

            bcsha256a.BlockUpdate(ba, 0, ba.Length);
            byte[] thehash = new byte[32];
            bcsha256a.DoFinal(thehash, 0);
            bcsha256a.BlockUpdate(thehash, 0, 32);
            bcsha256a.DoFinal(thehash, 0);
            for (int i = 0; i < 4; i++)
            {
                bb[ba.Length + i] = thehash[i];
            }
            return(Base58.FromByteArray(bb));
        }
Beispiel #29
0
        public static BigInteger Concatenate(this BigInteger start, params BigInteger[] rest)
        {
            var digest = new Sha256Digest();

            byte[] startBytes = start.ToByteArray();
            digest.BlockUpdate(startBytes, 0, startBytes.Length);
            foreach (var b in rest)
            {
                byte[] blockBytes = b.ToByteArray();
                digest.BlockUpdate(blockBytes, 0, blockBytes.Length);
            }

            digest.Finish();
            byte[] bytes = new byte[digest.GetDigestSize()];
            digest.DoFinal(bytes, 0);
            return(new BigInteger(bytes));
        }
        public static byte[] Hash256RawBytes(byte[] data, int offset, int count)
        {
#if NONATIVEHASH
            Sha256Digest sha256 = new Sha256Digest();
            sha256.BlockUpdate(data, offset, count);
            byte[] rv = new byte[32];
            sha256.DoFinal(rv, 0);
            sha256.BlockUpdate(rv, 0, rv.Length);
            sha256.DoFinal(rv, 0);
            return(rv);
#else
            using (var sha = new SHA256Managed())
            {
                var h = sha.ComputeHash(data, offset, count);
                return(sha.ComputeHash(h, 0, h.Length));
            }
#endif
        }