Exemplo n.º 1
0
        public byte[] CalculateKeccakHash(byte[] value)
        {
            var digest = new KeccakDigest(256);
            var output = new byte[digest.GetDigestSize()];

            digest.BlockUpdate(value, 0, value.Length);
            digest.DoFinal(output, 0);
            return(output);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Hashes the specified payload.
        /// </summary>
        /// <param name="payload">The payload.</param>
        /// <returns>The transaction hash.</returns>
        internal static byte[] Hasher(byte[] payload)
        {
            var hash       = new byte[32];
            var sha3Hasher = new KeccakDigest(256);

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

            return(hash);
        }
Exemplo n.º 3
0
        public static byte[] SHA3(this byte[] data)
        {
            KeccakDigest digest = new KeccakDigest(256);

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

            return(output);
        }
Exemplo n.º 4
0
        public string CalculateHash(string value)
        {
            var digest = new KeccakDigest(256);
            var output = new byte[digest.GetDigestSize()];
            var input  = Encoding.UTF8.GetBytes(value);

            digest.BlockUpdate(input, 0, input.Length);
            digest.DoFinal(output, 0);
            return(output.ToHex());
        }
Exemplo n.º 5
0
        public static byte[] Keccac256(byte[] data)
        {
            KeccakDigest k = new KeccakDigest(256);

            k.BlockUpdate(data, 0, data.Length);
            var hash = new byte[32];

            k.DoFinal(hash, 0);
            return(hash);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Keccak256 hashing algorithm
        /// </summary>
        /// <param name="StringIn"></param>
        /// <returns></returns>
        public static string Keccak256HexHashString(string StringIn)
        {
            var sha3 = new KeccakDigest(256);

            byte[] hash  = new byte[sha3.GetDigestSize()];
            byte[] value = Encoding.Default.GetBytes(StringIn);
            sha3.BlockUpdate(value, 0, value.Length);
            sha3.DoFinal(hash, 0);
            return(ToHex(hash, false));
        }
        /// <summary>
        /// Generates a SHA-3 hash of <paramref name="value"/>.
        /// </summary>
        /// <param name="value">The data to hash.</param>
        /// <returns>The hashed result.</returns>
        public static byte[] Sha3Keccack(this byte[] value)
        {
            var digest = new KeccakDigest(256);
            var output = new byte[digest.GetDigestSize()];

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

            return(output);
        }
Exemplo n.º 8
0
        public static byte[] Hash(byte[] bytes, int bitLength)
        {
            var digest = new KeccakDigest(bitLength);
            var output = new byte[digest.GetDigestSize()];

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

            return(output);
        }
Exemplo n.º 9
0
        protected static byte[] ComputeHash(byte[] bytes, int bits)
        {
            var digest = new KeccakDigest(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);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Returns message hash
        /// </summary>
        public static byte[] Keccak256(byte[] message, int offset, int size)
        {
            var kecc = new KeccakDigest(256);

            kecc.BlockUpdate(message, offset, size);
            var output = new byte[256];

            kecc.DoFinal(output, 0);

            return(output);
        }
Exemplo n.º 11
0
        public static byte[] Keccak256Helper(byte[] _input)
        {
            KeccakDigest Kec256 = new KeccakDigest(256);

            Kec256.Reset();
            byte[] resultHashedKec256 = new byte[32];
            Kec256.BlockUpdate(_input, 0, _input.Length);
            Kec256.DoFinal(resultHashedKec256, 0);

            return(resultHashedKec256);
        }
Exemplo n.º 12
0
        public static byte[] Keccak256(byte[] data, int offset, int length)
        {
            byte[] buffer = new byte[32];

            var keccakDigest = new KeccakDigest(256);

            keccakDigest.BlockUpdate(data, offset, length);
            keccakDigest.DoFinal(buffer, 0);

            return(buffer);
        }
Exemplo n.º 13
0
        private static byte[] DeriveAddress(PublicKey key)
        {
            byte[] hashPayload = key.Format(false).Skip(1).ToArray();
            var    digest      = new KeccakDigest(256);
            var    output      = new byte[digest.GetDigestSize()];

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

            return(output.Skip(output.Length - 20).ToArray());
        }
Exemplo n.º 14
0
        public static byte[] KeccakBytes(this IEnumerable <byte> message)
        {
            var bytes  = message as byte[] ?? message.ToArray();
            var digest = new KeccakDigest(256);

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

            digest.DoFinal(output, 0);
            return(output);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Produces a <see cref="PrivateKeyAccountClient"/> from a given <see cref="SecureString"/> of any size.
        /// </summary>
        /// <remarks>
        /// Takes a SecureString, hashes with Sha3 and converts the produced bytes to a 64 char hex string. The <see cref="StringUtils"/> class contains methods to convert to or from <see cref="SecureString"/>.
        /// </remarks>
        /// <param name="data">The data to convert to a private key.</param>
        /// <returns>A <see cref="PrivateKeyAccountClient"/> that can be used to initiate transactions.</returns>
        public PrivateKeyAccountClient FromNewDataPrivateKey(SecureString data)
        {
            var digestSha3 = new KeccakDigest(256);
            var dataBytes  = Encoding.Default.GetBytes(StringUtils.ConvertToUnsecureString(data));
            var pkBytes    = new byte[32];

            digestSha3.BlockUpdate(dataBytes, 0, 32);
            digestSha3.DoFinal(pkBytes, 0);
            var sk = StringUtils.ToSecureString(CryptoBytes.ToHexStringLower(pkBytes));

            return(FromPrivateKey(new PrivateKey(sk)));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Gets the SHA3 digest from the specified data.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns>The digest string.</returns>
        public static string GetSha3(MemoryStream data)
        {
            var digest = new KeccakDigest();

            digest.BlockUpdate(data.ToArray(), 0, (int)data.Length);

            var result = new byte[digest.GetDigestSize()];

            digest.DoFinal(result, 0);

            return(BitConverter.ToString(result).Replace("-", ""));
        }
Exemplo n.º 17
0
        // Original crypto_sign_open, for reference only

        /*public static int crypto_sign_open(
         * byte[] m, out int mlen,
         * byte[] sm, int smlen,
         * byte[] pk)
         * {
         *  byte[] h = new byte[64];
         *  byte[] checkr = new byte[32];
         *  GroupElementP3 A;
         *  GroupElementP2 R;
         *  int i;
         *
         *  mlen = -1;
         *  if (smlen < 64) return -1;
         *  if ((sm[63] & 224) != 0) return -1;
         *  if (GroupOperations.ge_frombytes_negate_vartime(out A, pk, 0) != 0) return -1;
         *
         *  for (i = 0; i < smlen; ++i) m[i] = sm[i];
         *  for (i = 0; i < 32; ++i) m[32 + i] = pk[i];
         *  Sha512BclWrapper.crypto_hash_sha512(h, m, 0, smlen);
         *  ScalarOperations.sc_reduce(h);
         *
         *  var sm32 = new byte[32];
         *  Array.Copy(sm, 32, sm32, 0, 32);
         *  GroupOperations.ge_double_scalarmult_vartime(out R, h, ref A, sm32);
         *  GroupOperations.ge_tobytes(checkr, 0, ref R);
         *  if (Helpers.crypto_verify_32(checkr, sm) != 0)
         *  {
         *      for (i = 0; i < smlen; ++i)
         *          m[i] = 0;
         *      return -1;
         *  }
         *
         *  for (i = 0; i < smlen - 64; ++i)
         *      m[i] = sm[64 + i];
         *  for (i = smlen - 64; i < smlen; ++i)
         *      m[i] = 0;
         *  mlen = smlen - 64;
         *  return 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 KeccakDigest(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);
        }
Exemplo n.º 18
0
        private byte[] CalculateHash(byte[] data)
        {
            var cloner = new byte[data.Length];

            Array.Copy(data, cloner, data.Length);
            var hasher = new KeccakDigest(256);

            hasher.BlockUpdate(cloner, 0, cloner.Length);
            var output = new byte[hasher.GetDigestSize()];

            hasher.DoFinal(output, 0);
            return(output);
        }
Exemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="trits"></param>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public override ICurl Absorb(sbyte[] trits, int offset, int length)
        {
            if (length % 243 != 0)
            {
                throw new IllegalStateException("Illegal length: " + length);
            }

            do
            {
                Array.Copy(trits, offset, _tritState, 0, HASH_LENGTH);

                //convert to bits
                _tritState[HASH_LENGTH - 1] = 0;
                FixedBigIntConverter.FromTritsToBytes(_tritState, _byteState);

                //run keccak
                _keccak.BlockUpdate(_byteState, 0, _byteState.Length);
                offset += HASH_LENGTH;
            } while ((length -= HASH_LENGTH) > 0);

            return(this);
        }
Exemplo n.º 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 Address(string publicKey, NetworkType.Types networkType)
        {
            // step 1) sha-3(256) public key
            var digestSha3 = new KeccakDigest(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.GetNetwork() }.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
            Initialize(stepSix.ToBase32String());
        }
Exemplo n.º 21
0
        public static byte[] Sha3(this byte[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            var digest = new KeccakDigest(256);
            var output = new byte[digest.GetDigestSize()];

            digest.BlockUpdate(value, 0, value.Length);
            digest.DoFinal(output, 0);
            return(output);
        }
Exemplo n.º 22
0
        public static void SetSecrets(EncryptionHandshake handshake, HandshakeRole handshakeRole)
        {
            byte[] ephemeralSharedSecret = Proxy.EcdhSerialized(handshake.RemoteEphemeralPublicKey.Bytes, handshake.EphemeralPrivateKey.KeyBytes);
            byte[] nonceHash             = Keccak.Compute(Bytes.Concat(handshake.RecipientNonce, handshake.InitiatorNonce)).Bytes;
            byte[] sharedSecret          = Keccak.Compute(Bytes.Concat(ephemeralSharedSecret, nonceHash)).Bytes;
            byte[] token     = Keccak.Compute(sharedSecret).Bytes;
            byte[] aesSecret = Keccak.Compute(Bytes.Concat(ephemeralSharedSecret, sharedSecret)).Bytes;
            Array.Clear(sharedSecret, 0, sharedSecret.Length);                   // TODO: it was passed in the concat for Keccak so not good enough
            byte[] macSecret = Keccak.Compute(Bytes.Concat(ephemeralSharedSecret, aesSecret)).Bytes;
            Array.Clear(ephemeralSharedSecret, 0, ephemeralSharedSecret.Length); // TODO: it was passed in the concat for Keccak so not good enough
            handshake.Secrets           = new EncryptionSecrets();
            handshake.Secrets.Token     = token;
            handshake.Secrets.AesSecret = aesSecret;
            handshake.Secrets.MacSecret = macSecret;

            KeccakDigest mac1 = new KeccakDigest(MacBitsSize);

            mac1.BlockUpdate(macSecret.Xor(handshake.RecipientNonce), 0, macSecret.Length);
            mac1.BlockUpdate(handshake.AuthPacket.Data, 0, handshake.AuthPacket.Data.Length);

            KeccakDigest mac2 = new KeccakDigest(MacBitsSize);

            mac2.BlockUpdate(macSecret.Xor(handshake.InitiatorNonce), 0, macSecret.Length);
            mac2.BlockUpdate(handshake.AckPacket.Data, 0, handshake.AckPacket.Data.Length);

            if (handshakeRole == HandshakeRole.Initiator)
            {
                handshake.Secrets.EgressMac  = mac1;
                handshake.Secrets.IngressMac = mac2;
            }
            else
            {
                handshake.Secrets.EgressMac  = mac2;
                handshake.Secrets.IngressMac = mac1;
            }
        }
Exemplo n.º 23
0
        /// <inheritdoc />
        /// <summary>
        /// </summary>
        /// <param name="trits"></param>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public override void Absorb(int[] trits, int offset, int length)
        {
            if (length % 243 != 0)
            {
                throw new IllegalStateException("Illegal length: " + length);
            }

            do
            {
                //copy trits[offset:offset+length]
                Array.Copy(trits, offset, _tritState, 0, HashLength);

                //convert to bits
                _tritState[HashLength - 1] = 0;
                FixedBigIntConverter.FromTritsToBytes(_tritState, _byteState);
                //BigIntConverter.BytesFromBigInt(
                //    BigIntConverter.BigIntFromTrits(_tritState, 0, HashLength),
                //    _byteState, 0, ByteHashLength);

                //run keccak
                _keccak.BlockUpdate(_byteState, 0, _byteState.Length);
                offset += HashLength;
            } while ((length -= HashLength) > 0);
        }
Exemplo n.º 24
0
        public static byte[] GenerateMac(byte[] derivekey, byte[] ciphertext)
        {
            int size = (int)(derivekey.Length * 0.5) + ciphertext.Length;

            byte[] input = new byte[size];
            Array.Copy(derivekey, 16, input, 0, 16);
            Array.Copy(ciphertext, 0, input, 16, ciphertext.Length);

            var digest = new KeccakDigest(256);
            var mac    = new byte[digest.GetDigestSize()];

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

            return(mac);
        }
Exemplo n.º 25
0
        public void CheckMac(byte[] input, int offset, int length, bool isHeader)
        {
            if (isHeader)
            {
                UpdateMac(_ingressMac, input, offset, input, offset + length, false); // TODO: confirm header is seed
            }
            else
            {
                _ingressMac.BlockUpdate(input, offset, length);

                // frame-mac: right128 of egress-mac.update(aes(mac-secret,egress-mac) ^ right128(egress-mac.update(frame-ciphertext).digest))
                byte[] buffer = new byte[_ingressMac.GetDigestSize()];
                DoFinalNoReset(_ingressMac, buffer, 0); // frame MAC seed
                UpdateMac(_ingressMac, buffer, 0, input, offset + length, false);
            }
        }
Exemplo n.º 26
0
        public void DJB_Ed25519_Keccak512()
        {
            byte[] data = TEST;

            var digest = new KeccakDigest(512);
            var m      = new byte[digest.OutputSize];

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

            ECKeypair keypair = KeypairFactory.GenerateECKeypair(DjbCurve.Ed25519.ToString());

            byte[] sig  = Ed25519.Sign(m, keypair.EncodedPrivateKey);
            bool   good = Ed25519.Verify(sig, m, keypair.EncodedPublicKey);

            Assert.IsTrue(good);
        }
Exemplo n.º 27
0
        public static void key_derive(byte[] shared, byte[] salt, byte[] secretKey, byte[] pubkey)
        {
            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 KeccakDigest(512);

            digestSha3.BlockUpdate(secretKey, 0, 32);
            digestSha3.DoFinal(longKeyHash, 0);

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

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

            ScalarOperations.sc_clamp(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.TweetNaCl.Unpackneg(q, pubkey); // returning -1 invalid signature

            TweetNaCl.TweetNaCl.Scalarmult(p, q, shortKeyHash, 0);

            TweetNaCl.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 KeccakDigest(256);

            digestSha3Two.BlockUpdate(shared, 0, 32);
            digestSha3Two.DoFinal(shared, 0);
        }
Exemplo n.º 28
0
        /// <summary>
        /// adapted from ethereumJ
        /// </summary>
        private byte[] UpdateMac(KeccakDigest mac, byte[] seed, int offset, byte[] output, int outOffset, bool egress)
        {
            byte[] aesBlock = new byte[mac.GetDigestSize()];
            DoFinalNoReset(mac, aesBlock, 0);

            // TODO: check if need to make a new one each time
            MakeMacCipher().ProcessBlock(aesBlock, 0, aesBlock, 0);

            // Note that although the mac digest size is 32 bytes, we only use 16 bytes in the computation
            int length = 16;

            for (int i = 0; i < length; i++)
            {
                aesBlock[i] ^= seed[i + offset];
            }

            mac.BlockUpdate(aesBlock, 0, length);

            byte[] result = new byte[mac.GetDigestSize()];
            DoFinalNoReset(mac, result, 0);

            if (egress)
            {
                Array.Copy(result, 0, output, outOffset, length);
            }
            else
            {
                bool isMacSame = true;
                for (int i = 0; i < length; i++)
                {
                    if (output[i + outOffset] != result[i])
                    {
                        isMacSame = false;
                        break;
                    }
                }

                if (!isMacSame)
                {
                    throw new IOException($"MAC mismatch from {_remoteNodeId}");
                }
            }

            return(result);
        }
Exemplo n.º 29
0
        public static PrivateKey Create()
        {
            var ng    = RandomNumberGenerator.Create();
            var bytes = new byte[2048];

            ng.GetNonZeroBytes(bytes);

            var digestSha3 = new KeccakDigest(256);
            var stepOne    = new byte[32];

            digestSha3.BlockUpdate(bytes, 0, 32);
            digestSha3.DoFinal(stepOne, 0);

            var pk = new PrivateKey(StringUtils.ToSecureString(CryptoBytes.ToHexStringLower(stepOne)));

            bytes   = null;
            stepOne = null;
            return(pk);
        }
Exemplo n.º 30
0
        public static EncryptionSecrets BuildSecretsWithSameIngressAndEgress()
        {
            EncryptionSecrets secrets = new EncryptionSecrets();

            secrets.AesSecret = AesSecret;
            secrets.MacSecret = MacSecret;

            byte[] bytes = AesSecret.Xor(MacSecret);

            KeccakDigest egressMac = new KeccakDigest(256);

            egressMac.BlockUpdate(bytes, 0, 32);
            secrets.EgressMac = egressMac;

            KeccakDigest ingressMac = new KeccakDigest(256);

            ingressMac.BlockUpdate(bytes, 0, 32);
            secrets.IngressMac = ingressMac;
            return(secrets);
        }