예제 #1
0
        public void Absorb(sbyte[] trits, int offset, int length)
        {
            if (((length % 243) != 0))
            {
                throw new Exception("Illegal length provided");
            }

            do
            {
                var limit = (length < Curl.HASH_LENGTH ? length : Curl.HASH_LENGTH);

                var trit_state = trits.Slice(offset, offset + limit);//.ToArray();
                offset += limit;

                // convert trit state to words
                var wordsToAbsorb = Words.trits_to_words(trit_state);


                var wordArray = ConvertIntArrayToByteArray(wordsToAbsorb);
                sha3Digest.BlockUpdate(wordArray, 0, wordArray.Length);

                // absorb the trit stat as wordarray
                //this.k.update(
                //    CryptoJS.lib.WordArray.create(wordsToAbsorb));
            } while ((length -= Curl.HASH_LENGTH) > 0);
        }
        public async Task SecretProofTransactionTest()
        {
            var signer = KeyPair.CreateFromPrivateKey(Config.PrivateKeyMain);

            var secretHash = new byte[64];

            var digest = new Sha3Digest(512);

            digest.BlockUpdate("5D8BEBBE80D7EA3B0088E59308D8671099781429".FromHex(), 0, "5D8BEBBE80D7EA3B0088E59308D8671099781429".FromHex().Length);
            digest.DoFinal(secretHash, 0);

            var trans = SecretProofTransaction.Create(
                NetworkType.Types.MIJIN_TEST,
                Deadline.CreateHours(2),
                0,
                HashType.Types.SHA3_512,
                secretHash.ToHexLower(),
                "5D8BEBBE80D7EA3B0088E59308D8671099781429")
                        .SignWith(signer);

            listener.ConfirmedTransactionsGiven(Address.CreateFromPublicKey(signer.PublicKeyString,
                                                                            NetworkType.Types.MIJIN_TEST)).Subscribe(e => Console.WriteLine(e.TransactionInfo.Hash));

            await new TransactionHttp(host).Announce(trans);

            var status = await listener.TransactionStatus(Address.CreateFromPublicKey(signer.PublicKeyString, NetworkType.Types.MIJIN_TEST)).Where(e => e.Hash == trans.Hash).Take(1);

            Assert.AreEqual("Failure_Lock_Secret_Already_Used", status.Status);
        }
예제 #3
0
        private static byte[] CalculateChecksum(byte[] pubkey)
        {
            // TORv3 CHECKSUM = H(".onion checksum" | PUBKEY | VERSION)[:2]
            var prefix = Encoders.ASCII.DecodeData(".onion checksum");

            var hasher = new Sha3Digest(256);

            hasher.BlockUpdate(prefix, 0, prefix.Length);
            hasher.BlockUpdate(pubkey, 0, pubkey.Length);
            hasher.Update((byte)3);

            var fullChecksum = new byte[hasher.GetByteLength()];

            hasher.DoFinal(fullChecksum, 0);
            return(fullChecksum.SafeSubarray(0, TORV3_ADDR_CHECKSUM_LEN));
        }
        public string Hash(string valueToHash, string salt, bool saveSaltInResult, int bitLength)
        {
            var fullText = string.Concat(valueToHash, salt);
            var data     = Encoding.UTF8.GetBytes(fullText);

            var sha3          = new Sha3Digest(bitLength);
            var hashedBytes   = new byte[sha3.GetDigestSize()];
            var toHashAsBytes = Encoding.ASCII.GetBytes(valueToHash);

            sha3.BlockUpdate(toHashAsBytes, 0, toHashAsBytes.Length);
            sha3.DoFinal(hashedBytes, 0);

            var asString = ByteArrayToString(hashedBytes);

            var algorithm = 0;

            if (bitLength == 512)
            {
                algorithm = (int)HashAlgorithm.SHA3_512;
            }
            else
            {
                throw new NotImplementedException($"Cannot find a HashAlgorithm for bit length: {bitLength}");
            }

            if (saveSaltInResult)
            {
                return(string.Format("[{0}]{1}{2}", algorithm, salt, asString));
            }
            else
            {
                return(string.Format("[{0}]{1}", algorithm, asString));
            }
        }
예제 #5
0
 protected override void HashCore(byte[] array, int ibStart, int cbSize)
 {
     if (HashValue == null)
     {
         Initialize();
     }
     _digest.BlockUpdate(array, ibStart, cbSize);
 }
예제 #6
0
        public static byte[] ComputeSha3Hash(byte[] data)
        {
            var shaHash = new Sha3Digest();

            shaHash.BlockUpdate(data, 0, data.Length);
            byte[] hashedValue = new byte[shaHash.GetDigestSize()];
            shaHash.DoFinal(hashedValue, 0);
            return(hashedValue);
        }
        /// <summary>
        ///     Hash an array of bytes using Sha3 256 algorithm.
        /// </summary>
        /// <param name="bytes">The bytes.</param>
        /// <returns>System.Byte[].</returns>
        public static byte[] Sha3_256(byte[] bytes)
        {
            var temp   = new byte[32];
            var digest = new Sha3Digest(256);

            digest.BlockUpdate(bytes, 0, bytes.Length);
            digest.DoFinal(temp, 0);
            return(temp);
        }
예제 #8
0
        public static byte[] ComputeSha3Digest(byte[] data, int bitLength)
        {
            var digest = new Sha3Digest(bitLength);

            byte[] buffer = new byte[digest.GetDigestSize()];
            digest.BlockUpdate(data, 0, data.Length);
            digest.DoFinal(buffer, 0);
            return(buffer);
        }
예제 #9
0
        public byte[] CalculateSha3Hash(byte[] value)
        {
            var digest = new Sha3Digest(256);
            var output = new byte[digest.GetDigestSize()];

            digest.BlockUpdate(value, 0, value.Length);
            digest.DoFinal(output, 0);
            return(output);
        }
예제 #10
0
        private static byte[] ComputeSha3Hash(this byte[] input, int bitLength)
        {
            var hashAlgo = new Sha3Digest(bitLength);

            hashAlgo.BlockUpdate(input, 0, input.Length);
            var output = new byte[bitLength / 8];

            hashAlgo.DoFinal(output, 0);
            return(output);
        }
예제 #11
0
        private Hash CalculateHash(byte[] bytes)
        {
            Sha3Digest digest = new Sha3Digest(256);

            digest.BlockUpdate(bytes, 0, bytes.Length);
            byte[] result = new byte[32];
            digest.DoFinal(result, 0);

            return(new Hash(result));
        }
예제 #12
0
        /// <summary>
        /// Computes the SHA3 hash
        /// </summary>
        /// <param name="data"></param>
        /// <param name="bitLength"></param>
        /// <returns></returns>
        private byte[] ComputeSHA3(byte[] data, int bitLength)
        {
            var digest = new Sha3Digest(bitLength);

            digest.BlockUpdate(data, 0, data.Length);
            var result = new byte[digest.GetDigestSize()];

            digest.DoFinal(result, 0);
            return(result);
        }
예제 #13
0
        public static Hash32 Digest(byte[] bytes)
        {
            var sha3 = new Sha3Digest();

            sha3.BlockUpdate(bytes, 0, bytes.Length);

            bytes = new byte[32];
            sha3.DoFinal(bytes, 0);
            return(new Hash32(bytes));
        }
예제 #14
0
        /// <summary>
        /// Hash data with SHA3
        /// </summary>
        /// <param name="data">Data to hash</param>
        /// <param name="bitLength">Size in bits</param>
        /// <returns>Hash</returns>
        public static byte[] Hash(byte[] data, int bitLength = 512)
        {
            byte[] result = new byte[bitLength / 8];

            Sha3Digest sha3 = new Sha3Digest(bitLength);

            sha3.BlockUpdate(data, 0, data.Length);
            sha3.DoFinal(result, 0);

            return(result);
        }
예제 #15
0
        private static byte[] Sha256(string data)
        {
            var input  = Encoding.UTF8.GetBytes(data);
            var digest = new Sha3Digest(256);
            var output = new byte[digest.GetDigestSize()];

            digest.BlockUpdate(input, 0, input.Length);
            digest.DoFinal(output, 0);

            return(output);
        }
예제 #16
0
        private Hash CalculateHash()
        {
            Sha3Digest digest = new Sha3Digest(256);

            byte[] bytes = BlockHeaderEncoder.Instance.Encode(this);
            digest.BlockUpdate(bytes, 0, bytes.Length);
            byte[] result = new byte[32];
            digest.DoFinal(result, 0);

            return(new Hash(result));
        }
예제 #17
0
        protected static byte[] ComputeHash(byte[] bytes, int bits)
        {
            var digest = new Sha3Digest(bits);
            var output = new byte[digest.GetDigestSize()];

            byte[] message = bytes ?? new byte[0];
            digest.BlockUpdate(message, 0, message.Length);
            digest.DoFinal(output, 0);

            return(output);
        }
예제 #18
0
        /// <summary>
        /// Computes the SHA3 hash value for the specified byte array.
        /// </summary>
        /// <param name="bitLength">Output size of hash in bits.</param>
        /// <param name="buffer">The input to compute the hash code for.</param>
        /// <returns>The computed hash code.</returns>
        public static byte[] ComputeHash(int bitLength, byte[] buffer)
        {
            var hashAlgorithm = new Sha3Digest(bitLength);

            hashAlgorithm.BlockUpdate(buffer, 0, buffer.Length);

            var computedHashCode = new byte[bitLength / 8];

            hashAlgorithm.DoFinal(computedHashCode, 0);

            return(computedHashCode);
        }
예제 #19
0
        public static bool crypto_sign_verify(
            byte[] sig, int sigoffset,
            byte[] m, int moffset, int mlen,
            byte[] pk, int pkoffset)
        {
            byte[]         checkr = new byte[32];
            GroupElementP3 A;
            GroupElementP2 R;

            if ((sig[sigoffset + 63] & 224) != 0)
            {
                return(false);
            }
            if (GroupOperations.ge_frombytes_negate_vartime(out A, pk, pkoffset) != 0)
            {
                return(false);
            }
            var hash = new Sha3Digest(512);

            hash.BlockUpdate(sig, sigoffset, 32);
            hash.BlockUpdate(pk, pkoffset, 32);
            hash.BlockUpdate(m, moffset, mlen);
            var b = new byte[64];

            hash.DoFinal(b, 0);


            ScalarOperations.sc_reduce(b);

            var sm32 = new byte[32];//todo: remove allocation

            Array.Copy(sig, sigoffset + 32, sm32, 0, 32);
            GroupOperations.ge_double_scalarmult_vartime(out R, b, ref A, sm32);
            GroupOperations.ge_tobytes(checkr, 0, ref R);
            var result = CryptoBytes.ConstantTimeEquals(checkr, 0, sig, sigoffset, 32);

            CryptoBytes.Wipe(b);
            CryptoBytes.Wipe(checkr);
            return(result);
        }
예제 #20
0
        /// <summary>
        /// Create an Address from a given public key and network type.
        /// </summary>
        /// <param name="publicKey">The public key.</param>
        /// <param name="networkType">The network type</param>
        /// <returns>Address.</returns>
        public static Address CreateFromPublicKey(string publicKey, NetworkType.Types networkType)
        {
            // step 1) sha-3(256) public key
            var digestSha3 = new Sha3Digest(256);
            var stepOne    = new byte[Constants.Key];

            digestSha3.BlockUpdate(publicKey.FromHex(), 0, Constants.Key);
            digestSha3.DoFinal(stepOne, 0);

            // step 2) perform ripemd160 on previous step
            var digestRipeMd160 = new RipeMD160Digest();
            var stepTwo         = new byte[Constants.Ripemd160];

            digestRipeMd160.BlockUpdate(stepOne, 0, Constants.Key);
            digestRipeMd160.DoFinal(stepTwo, 0);

            // step3) prepend network byte
            var stepThree = new [] { networkType.GetNetworkByte() }.Concat(stepTwo).ToArray();

            // step 4) perform sha3 on previous step
            var stepFour = new byte[Constants.Key];

            digestSha3.BlockUpdate(stepThree, 0, Constants.Ripemd160 + 1);
            digestSha3.DoFinal(stepFour, 0);

            // step 5) retrieve checksum
            var stepFive = new byte[Constants.Checksum];

            Array.Copy(stepFour, 0, stepFive, 0, Constants.Checksum);

            // step 6) append stepFive to resulst of stepThree
            var stepSix = new byte[Constants.AddressDecoded];

            Array.Copy(stepThree, 0, stepSix, 0, Constants.Ripemd160 + 1);
            Array.Copy(stepFive, 0, stepSix, Constants.Ripemd160 + 1, Constants.Checksum);

            // step 7) return base 32 encode address byte array
            return(CreateFromEncoded(stepSix.ToBase32String()));
        }
예제 #21
0
        /// <summary>
        ///     SAH3 hash of [data].
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] Sha3(byte[] data)
        {
            Guard.NotNull(data, nameof(data));
            Guard.NotLessThanOrEqualTo(data.Length, 0, nameof(data));

            var digest = new Sha3Digest(512);

            digest.BlockUpdate(data, 0, data.Length);
            var result = new byte[64]; // 512 / 8 = 64

            digest.DoFinal(result, 0);
            return(result);
        }
예제 #22
0
        public static ExternalAddress Create(PublicKey publicKey)
        {
            byte[] bytes = publicKey.Binary.Skip(1).ToArray();

            var sha3 = new Sha3Digest();

            sha3.BlockUpdate(bytes, 0, bytes.Length);

            bytes = new byte[32];
            sha3.DoFinal(bytes, 0);

            return(new ExternalAddress(bytes.Skip(12)));
        }
예제 #23
0
        public byte[] Hash(string password, IEnumerable <byte> salt)
        {
            var bytes = Encoding.ASCII.GetBytes(password).ToList();

            bytes.AddRange(salt);

            _hashAlgorithm.BlockUpdate(bytes.ToArray(), 0, bytes.Count);
            var result = new byte[BitLength / 8];

            _hashAlgorithm.DoFinal(result, 0);

            return(result);
        }
        //This class handles the mining of the block based on the transactions in a block + datetime stamp (utc) + previous hash

        public Hash CalculateHash(Hash _parentHash, IList <BlockTransaction> _unconfirmedTransactions, DateTime _dateTimeStampBlock)
        {
            byte[] Input = BlockMiningManager.GenerateBytes(_parentHash != null? Convert.ToString(_parentHash.GetHashCode()):"", _dateTimeStampBlock.ToString(), Convert.ToString(_unconfirmedTransactions.GetHashCode()));

            //Design decision, vary difficulty by using PBKDF2 or maintain SHA3 256...later to be decided
            Sha3Digest digest = new Sha3Digest(256);

            digest.BlockUpdate(Input, 0, Input.Length);
            byte[] result = new byte[32];
            digest.DoFinal(result, 0);

            return(new Hash(result));
        }
예제 #25
0
        public static byte[] GetAddressHash(byte[] publicKey)
        {
            var digest = new Sha3Digest(256);
            var output = new byte[digest.GetDigestSize()];

            digest.BlockUpdate(publicKey, 0, publicKey.Length);
            digest.DoFinal(output, 0);

            var result = new byte[20];

            Array.Copy(output, output.Length - 20, result, 0, 20);

            return(result);
        }
예제 #26
0
        /// <summary>
        /// Generates an in based on parentId and name
        /// </summary>
        /// <param name="parentId">The 64 bit id of the parent namespace.</param>
        /// <param name="name">The name of the bottom most namespace or mosaic.</param>
        /// <returns type="long">The 64 bit id.</returns>
        internal static ulong GenerateId(ulong parentId, string name)
        {
            var p    = BitConverter.GetBytes(parentId);
            var n    = Encoding.UTF8.GetBytes(name);
            var hash = new Sha3Digest(256);

            hash.BlockUpdate(p.Concat(n).ToArray(), 0, p.Length + n.Length);

            var result = new byte[32];

            hash.DoFinal(result, 0);

            return((ulong)BitConverter.ToInt64(result, 0));
        }
        /// <summary>
        /// Hashers the specified payload.
        /// </summary>
        /// <param name="payload">The payload.</param>
        /// <returns>The transaction hash.</returns>
        internal static byte[] Hasher(byte[] payload)
        {
            var sigAndKey = payload.Take(4, 32)
                            .Concat(
                payload.Take(4 + 64, payload.Length - (4 + 64))
                ).ToArray();

            var hash       = new byte[32];
            var sha3Hasher = new Sha3Digest(256);

            sha3Hasher.BlockUpdate(sigAndKey, 0, sigAndKey.Length);
            sha3Hasher.DoFinal(hash, 0);

            return(hash);
        }
예제 #28
0
        public static ulong GenerateNsId(ulong parentId, string name)
        {
            var pBytes = BitConverter.GetBytes(parentId);
            var nBytes = Encoding.UTF8.GetBytes(name);

            var hash = new Sha3Digest(256);

            hash.BlockUpdate(pBytes.Concat(nBytes).ToArray(), 0, pBytes.Length + nBytes.Length);

            var result = new byte[32];

            hash.DoFinal(result, 0);

            return((ulong)BitConverter.ToInt64(result, 0) | 0x8000000000000000);
        }
        private string Hash(string password)
        {
            Sha3Digest hashAlgorithm = new Sha3Digest(512);

            // Choose correct encoding based on your usecase
            byte[] input = Encoding.UTF8.GetBytes(password);

            hashAlgorithm.BlockUpdate(input, 0, input.Length);

            byte[] result = new byte[64]; // 512 / 8 = 64
            hashAlgorithm.DoFinal(result, 0);

            string hashString = BitConverter.ToString(result);

            return(hashString.Replace("-", "").ToLowerInvariant());
        }
예제 #30
0
        /*
         * Copied from nem2-sdk Ed25519.derive_key
         */
        private static byte[] GetSecretKey(byte[] salt, string privateKey, string publicKey)
        {
            var shared       = new byte[32];
            var longKeyHash  = new byte[64];
            var shortKeyHash = new byte[32];

//            Array.Reverse(secretKey);

            // compute  Sha3(512) hash of secret key (as in prepareForScalarMultiply)
            var digestSha3 = new Sha3Digest(512);

            digestSha3.BlockUpdate(privateKey.FromHex(), 0, 32);
            digestSha3.DoFinal(longKeyHash, 0);

            longKeyHash[0]  &= 248;
            longKeyHash[31] &= 127;
            longKeyHash[31] |= 64;

            Array.Copy(longKeyHash, 0, shortKeyHash, 0, 32);

            ScalarOperationClamp(shortKeyHash, 0);

            var p = new[] { new long[16], new long[16], new long[16], new long[16] };
            var q = new[] { new long[16], new long[16], new long[16], new long[16] };

            TweetNaCl.Unpackneg(q, publicKey.FromHex()); // returning -1 invalid signature
            TweetNaCl.Scalarmult(p, q, shortKeyHash, 0);
            TweetNaCl.Pack(shared, p);

            // for some reason the most significant bit of the last byte needs to be flipped.
            // doesnt seem to be any corrosponding action in nano/nem.core, so this may be an issue in one of the above 3 functions. i have no idea.
            shared[31] ^= (1 << 7);

            // salt
            for (var i = 0; i < salt.Length; i++)
            {
                shared[i] ^= salt[i];
            }

            // hash salted shared key
            var digestSha3Two = new Sha3Digest(256);

            digestSha3Two.BlockUpdate(shared, 0, 32);
            digestSha3Two.DoFinal(shared, 0);

            return(shared);
        }