}// DeriveKey() internal static void DeriveKey(HMAC keyedHmac, ArraySegment<byte> bufferSegment, ArraySegment<byte> derivedOutput, uint counter = 1) { int derivedOutputCount = derivedOutput.Count, derivedOutputOffset = derivedOutput.Offset; byte[] K_i = null; HMAC2 keyedHmac2 = keyedHmac as HMAC2; checked { // Calculate each K_i value and copy the leftmost bits to the output buffer as appropriate. for (var counterStruct = new Utils.IntStruct { UintValue = counter }; derivedOutputCount > 0; ++counterStruct.UintValue) { counterStruct.ToBEBytes(bufferSegment.Array, bufferSegment.Offset); // update the counter within the buffer if (keyedHmac2 == null) { K_i = keyedHmac.ComputeHash(bufferSegment.Array, bufferSegment.Offset, bufferSegment.Count); } else { keyedHmac2.TransformBlock(bufferSegment.Array, bufferSegment.Offset, bufferSegment.Count, null, 0); keyedHmac2.TransformFinalBlock(bufferSegment.Array, 0, 0); K_i = keyedHmac2.HashInner; } // copy the leftmost bits of K_i into the output buffer int numBytesToCopy = derivedOutputCount > K_i.Length ? K_i.Length : derivedOutputCount;//Math.Min(derivedOutputCount, K_i.Length); Utils.BlockCopy(K_i, 0, derivedOutput.Array, derivedOutputOffset, numBytesToCopy); derivedOutputOffset += numBytesToCopy; derivedOutputCount -= numBytesToCopy; }// for }// checked if (keyedHmac2 == null && K_i != null) Array.Clear(K_i, 0, K_i.Length); /* clean up needed only when HMAC implementation is not HMAC2 */ }// DeriveKey()
}// DeriveKey() internal static void DeriveKey(HMAC keyedHmac, ArraySegment<byte> bufferSegment, ArraySegment<byte> derivedOutput, uint counter = 1) { int derivedOutputCount = derivedOutput.Count, derivedOutputOffset = derivedOutput.Offset; byte[] K_i = null; checked { // Calculate each K_i value and copy the leftmost bits to the output buffer as appropriate. for (var counterStruct = new Utils.IntStruct { UintValue = counter }; derivedOutputCount > 0; ++counterStruct.UintValue) { counterStruct.ToBEBytes(bufferSegment.Array, bufferSegment.Offset); // update the counter within the buffer K_i = keyedHmac.ComputeHash(bufferSegment.Array, bufferSegment.Offset, bufferSegment.Count); // copy the leftmost bits of K_i into the output buffer int numBytesToCopy = Math.Min(derivedOutputCount, K_i.Length); Utils.BlockCopy(K_i, 0, derivedOutput.Array, derivedOutputOffset, numBytesToCopy); derivedOutputOffset += numBytesToCopy; derivedOutputCount -= numBytesToCopy; }// for }// checked if (K_i != null) Array.Clear(K_i, 0, K_i.Length); }// DeriveKey()