Derive.cs

Contains the functions needed to derive the key and IV

// ------------------------------------------------------------------------------------------
// <copyright file="Derive.cs" company="Pointsharp AB">
//   Pointsharp AB
// </copyright>
// <summary>
//   Defines the Client partial class.
// </summary>
// ------------------------------------------------------------------------------------------

namespace SecMaker.NiP.Client
{
	using System;
	using System.Linq;

	public partial class Client
	{
		private void Derive()
		{
            var keySize = _symmetricalKeySize / 8;
            var ivSize = keySize / 2;

            _key =
				DeriveKey(_cltNonce, _srvNonce, _dateTimeKey, "key", 1, keySize);

			_iv =
				DeriveKey(_cltNonce, _srvNonce, _dateTimeKey, "iv", _counter, ivSize);
		}

		private byte[] DeriveKey(byte[] cltNonce, byte[] srvNonce, byte[] key, string keyType, int count, int size)
		{
			var typeBytes =
				Utility.ToBytes(keyType);

			var keyData =
				new byte[0];

			var counter =
				count;

			while (keyData.Length < size)
			{
				var sCount =
					Convert.ToString(counter);

				var countBytes =
					Utility.ToBytes(sCount);

				var bytes =
					srvNonce.Concat(cltNonce).Concat(typeBytes).Concat(countBytes).ToArray();

				keyData =
					keyData.Concat(
						Utility.GenerateHmac(
							_sHashAlg,
							bytes,
							key)
							.Take(size)).ToArray();

				counter++;
			}

			var data =
				keyData.Take(size).ToArray();

			return data;
		}
	}
}