Example #1
0
        private void RandomTest(SecureRandom random)
        {
            byte[] key = new byte[16];
            random.NextBytes(key);

            int length = 1 + random.Next(1024);

            byte[] input = new byte[length];
            random.NextBytes(input);

            SipHash mac = new SipHash();

            mac.Init(new KeyParameter(key));

            UpdateMac(mac, input, UPDATE_BYTES);
            long result1 = mac.DoFinal();

            UpdateMac(mac, input, UPDATE_FULL);
            long result2 = mac.DoFinal();

            UpdateMac(mac, input, UPDATE_MIX);
            long result3 = mac.DoFinal();

            if (result1 != result2 || result1 != result3)
            {
                Fail("Inconsistent results in random test");
            }
        }
Example #2
0
        public void TestBattery()
        {
            // 128-bit key
            var key = Enumerable.Range(0, 16).Select(x => (byte)x).ToArray();

            // SipHash initialized with the key
            var prf = new SipHash(key);

            // Perform the test battery
            var message = new byte[vectors.Length];

            for (int i = 0; i < vectors.Length; i++)
            {
                message[i] = (byte)i;

                // Compute the tag
                var tag = prf.Compute(message, 0, i);
                // Get the target tag
                var targetTag = BitConverter.ToInt64(vectors[i].Select(x => (byte)x).ToArray(), 0);

                if (tag != targetTag)
                {
                    throw new Exception(string.Format("Test vector failed for {0:N}-byte message!", i));
                }
            }
        }
Example #3
0
        private void RunMac(byte[] key, byte[] input, int updateType)
        {
            long expected = unchecked ((long)0xa129ca6149be45e5);

            SipHash mac = new SipHash();

            mac.Init(new KeyParameter(key));

            UpdateMac(mac, input, updateType);

            long result = mac.DoFinal();

            if (expected != result)
            {
                Fail("Result does not match expected value for DoFinal()");
            }

            // NOTE: Little-endian representation of 0xa129ca6149be45e5
            byte[] expectedBytes = Hex.Decode("e545be4961ca29a1");

            UpdateMac(mac, input, updateType);

            byte[] output = new byte[mac.GetMacSize()];
            int    len    = mac.DoFinal(output, 0);

            if (len != output.Length)
            {
                Fail("Result length does not equal GetMacSize() for DoFinal(byte[],int)");
            }
            if (!AreEqual(expectedBytes, output))
            {
                Fail("Result does not match expected value for DoFinal(byte[],int)");
            }
        }
Example #4
0
        private static void BenchmarkSipHash(int iterations, int length, Action <string> writeLine)
        {
            // Initialize SipHash engine with a random key
            var siphash = new SipHash(GetRandomBytes(16));

            // Generate specified amount of random data
            var data = GetRandomBytes(length);

            // Benchmark
            var stopWatch = Stopwatch.StartNew();

            for (int i = 0; i < iterations; i++)
            {
                siphash.Compute(data, 0, data.Length);
            }
            var elapsed = stopWatch.Elapsed;

            if (writeLine != null)
            {
                writeLine("SipHash benchmark results:");
                writeLine(string.Format(CultureInfo.CurrentUICulture, "- Digested {0} {1} times", BytesToString(data.Length), iterations));
                writeLine(string.Format(CultureInfo.CurrentUICulture, "- Elapsed: {0}", elapsed.ToString(@"hh\:mm\:ss\.fff")));
                writeLine(string.Format(CultureInfo.CurrentUICulture, "- Speed: {0}/s", BytesToString(data.Length / elapsed.TotalSeconds * iterations)));
            }
        }
Example #5
0
        public void Hash64_InvalidKeyLength_Throws(int keyLength)
        {
            var invalidKey = new byte[keyLength];
            var buffer     = new byte[0];

            Assert.Throws <ArgumentException>(() => SipHash.Hash64(buffer, invalidKey));
        }
Example #6
0
 public override int GetHashCode()
 {
     if (!_hashCode.HasValue)
     {
         _hashCode = SipHash.GetHashCode(KeyBytes);
     }
     return(_hashCode.Value);
 }
        public IActionResult Post(ICollection <IFormFile> files)
        {
            _logger.LogInformation("CPAPI: Post");

            try
            {
                // Get the siphash key from secret/environment variable
                string siphashKey = Utils.GetSecretOrEnvVar(ConfigurationProperties.HashKey, this.Configuration, this._logger).Trim();
                // validate tika base address
                if (siphashKey == "")
                {
                    _logger.LogWarning("Hash key not valid - cannot generate hash");
                    return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError));
                }
                else
                {
                    _logger.LogDebug("Hash key loaded");
                }
                byte[] siphashKeyBytes = System.Text.Encoding.ASCII.GetBytes(siphashKey);


                // Check that only one file has been uploaded
                if (files.Count != 1)
                {
                    return(BadRequest());
                }
                if (files.FirstOrDefault().Length == 0)
                {
                    return(BadRequest());
                }

                // Get the bytes from the file
                MemoryStream stream = new MemoryStream();
                files.FirstOrDefault().CopyTo(stream);
                byte[] fileBytes = stream.ToArray();

                // Calculate the hash
                System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
                SipHash hasher     = new SipHash(siphashKeyBytes);
                long    hashResult = hasher.Compute(fileBytes);
                stopwatch.Stop();
                _logger.LogDebug("Hash time (ms): " + stopwatch.ElapsedMilliseconds.ToString());

                // Convert to JSON
                string hasResultAsJson = JsonConvert.SerializeObject(hashResult, Formatting.None);

                // Return final result
                ObjectResult result = new ObjectResult(hasResultAsJson);
                return(result);
            }
            catch (Exception hashEx)
            {
                _logger.LogError("Hash Controller: " + hashEx.Message);
                return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError));
            }
        }
        public string CalculateHash(string message, string littleEndianKey)
        {
            var messageBytes = Encoding.ASCII.GetBytes(message);
            var byteKey      = BigInteger.Parse(littleEndianKey, NumberStyles.HexNumber).ToByteArray();
            var hasher       = new SipHash(byteKey);
            var hash         = hasher.ComputeHash(messageBytes);
            var stringHash   = BitConverter.ToUInt64(hash, 0).ToString("X");

            return(PadHash(stringHash));
        }
Example #9
0
        private UInt32 sipnode(UInt64 k0, UInt64 k1, UInt32 edgeMask, UInt32 nonce, byte uorv)
        {
            var key = new byte[16];

            BitConverter.GetBytes(k0).CopyTo(key, 0);
            BitConverter.GetBytes(k1).CopyTo(key, 8);

            var node = (UInt32)(SipHash.SipHash24((UInt64)(2 * nonce + uorv), k0, k1) & edgeMask);

            return((node << 1) | uorv);
        }
Example #10
0
        /// <summary>
        /// テキストのハッシュを64ビット値で返す。
        /// </summary>
        /// <param name="text">テキスト</param>
        /// <returns>テキストのハッシュ(64ビット)</returns>
        public static long ComputeSipHash(string text)
        {
            //// 16バイトの鍵を生成する。
            byte[] key = Encoding.ASCII.GetBytes("dWV9#LeZGa8eu7Hx");

            SipHash mac = new SipHash();

            mac.Init(new KeyParameter(key));

            //// テキストのハッシュを算出する。
            byte[] arrayOfText = Encoding.UTF8.GetBytes(text);
            mac.BlockUpdate(arrayOfText, 0, arrayOfText.Length);
            var result = mac.DoFinal();

            return(result);
        }
Example #11
0
        public void Hash64_TestVectors()
        {
            const int numVectors = 64;

            for (int i = 0; i < numVectors; ++i)
            {
                var buffer = new byte[i];
                for (int j = 0; j < i; j++)
                {
                    buffer[j] = (byte)j;
                }
                var result         = SipHash.Hash64(buffer, key);
                var expectedResult = BitConverter.ToUInt64(vectors[i], startIndex: 0);
                Debug.WriteLine("testing iteration #" + i);
                Assert.AreEqual(expectedResult, result);
            }
        }
Example #12
0
        public void TestBattery()
        {
            // 128-bit key
            var key = Enumerable.Range(0, 16).Select(x => (byte)x).ToArray();

            // SipHash initialized with the key
            var prf = new SipHash(key);

            // Perform the test battery
            var message = new byte[vectors.Length];

            for (int i = 0; i < vectors.Length; i++)
            {
                message[i] = (byte)i;

                // Compute the tag
                var tag = prf.Compute(message.AsSpan(0, i));
                // Get the target tag
                var targetTag = BitConverter.ToUInt64(vectors[i].Select(x => (byte)x).ToArray(), 0);

                Assert.True(tag == targetTag, $"Test vector failed for {i:N}-byte message!");
            }
        }
Example #13
0
        private void UpdateMac(SipHash mac, byte[] input, int updateType)
        {
            switch (updateType)
            {
            case UPDATE_BYTES:
            {
                for (int i = 0; i < input.Length; ++i)
                {
                    mac.Update(input[i]);
                }
                break;
            }

            case UPDATE_FULL:
            {
                mac.BlockUpdate(input, 0, input.Length);
                break;
            }

            case UPDATE_MIX:
            {
                int step = System.Math.Max(1, input.Length / 3);
                int pos  = 0;
                while (pos < input.Length)
                {
                    mac.Update(input[pos++]);
                    int len = System.Math.Min(input.Length - pos, step);
                    mac.BlockUpdate(input, pos, len);
                    pos += len;
                }
                break;
            }

            default:
                throw new InvalidOperationException();
            }
        }
Example #14
0
        public override void PerformTest()
        {
            byte[] key   = Hex.Decode("000102030405060708090a0b0c0d0e0f");
            byte[] input = Hex.Decode("000102030405060708090a0b0c0d0e");

            long expected = unchecked ((long)0xa129ca6149be45e5);

            SipHash mac = new SipHash();

            mac.Init(new KeyParameter(key));
            mac.BlockUpdate(input, 0, input.Length);

            long result = mac.DoFinal();

            if (expected != result)
            {
                Fail("Result does not match expected value for DoFinal()");
            }

            // NOTE: Little-endian representation of 0xa129ca6149be45e5
            byte[] expectedBytes = Hex.Decode("e545be4961ca29a1");

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

            byte[] output = new byte[mac.GetMacSize()];
            int    len    = mac.DoFinal(output, 0);

            if (len != output.Length)
            {
                Fail("Result length does not equal GetMacSize() for DoFinal(byte[],int)");
            }
            if (!AreEqual(expectedBytes, output))
            {
                Fail("Result does not match expected value for DoFinal(byte[],int)");
            }
        }
Example #15
0
        public void ReferenceTest()
        {
            ulong[] expected =
            {
                0x726fdb47dd0e0e31,
                0x74f839c593dc67fd,
                0x0d6c8009d9a94f5a,
                0x85676696d7fb7e2d,
                0xcf2794e0277187b7,
                0x18765564cd99a68d,
                0xcbc9466e58fee3ce,
                0xab0200f58b01d137,
                0x93f5f5799a932462,
                0x9e0082df0ba9e4b0,
                0x7a5dbbc594ddb9f3,
                0xf4b32f46226bada7,
                0x751e8fbc860ee5fb,
                0x14ea5627c0843d90,
                0xf723ca908e7af2ee,
                0xa129ca6149be45e5,
                0x3f2acc7f57c29bdb,
                0x699ae9f52cbe4794,
                0x4bc1b3f0968dd39c,
                0xbb6dc91da77961bd,
                0xbed65cf21aa2ee98,
                0xd0f2cbb02e3b67c7,
                0x93536795e3a33e88,
                0xa80c038ccd5ccec8,
                0xb8ad50c6f649af94,
                0xbce192de8a85b8ea,
                0x17d835b85bbb15f3,
                0x2f2e6163076bcfad,
                0xde4daaaca71dc9a5,
                0xa6a2506687956571,
                0xad87a3535c49ef28,
                0x32d892fad841c342,
                0x7127512f72f27cce,
                0xa7f32346f95978e3,
                0x12e0b01abb051238,
                0x15e034d40fa197ae,
                0x314dffbe0815a3b4,
                0x027990f029623981,
                0xcadcd4e59ef40c4d,
                0x9abfd8766a33735c,
                0x0e3ea96b5304a7d0,
                0xad0c42d6fc585992,
                0x187306c89bc215a9,
                0xd4a60abcf3792b95,
                0xf935451de4f21df2,
                0xa9538f0419755787,
                0xdb9acddff56ca510,
                0xd06c98cd5c0975eb,
                0xe612a3cb9ecba951,
                0xc766e62cfcadaf96,
                0xee64435a9752fe72,
                0xa192d576b245165a,
                0x0a8787bf8ecb74b2,
                0x81b3e73d20b49b6f,
                0x7fa8220ba3b2ecea,
                0x245731c13ca42499,
                0xb78dbfaf3a8d83bd,
                0xea1ad565322a1a0b,
                0x60e61c23a3795013,
                0x6606d7e446282b93,
                0x6ca4ecb15c5f91e1,
                0x9f626da15c9625f3,
                0xe51b38608ef25f57,
                0x958a324ceb064572,
            };
            ulong k0 = 0x0706050403020100;
            ulong k1 = 0x0f0e0d0c0b0a0908;

            byte[] data = Enumerable.Range(0, expected.Length).Select(x => (byte)x).ToArray();
            for (int i = 0; i != data.Length; ++i)
            {
                Assert.AreEqual(expected[i], SipHash.ComputeHash(data, 0, i, k0, k1));
            }
        }
Example #16
0
 public void Hash64_NullArgs_Throws()
 {
     Assert.Throws <ArgumentNullException>(() => SipHash.Hash64(null, key));
     Assert.Throws <ArgumentNullException>(() => SipHash.Hash64(key, null));
 }