TLS HMAC and the Pseudorandom Function Simplification Assistance
-
I'm currently studying cryptography implementation in depth. To that end I'm reading various RFCs and trying to implement the algorithms so I can get a better understanding of them and hopefully make my applications more secure when cryptography is used. Right now I'm reading the TLS RFC 5246. The first algorithm in the document is a pseudorandom function (PRF) that takes a secret, a seed, and a label and produces an output of a specified length. This is Section 5 (Page 14 in the PDF) of the document. It defines a function called
P_hash(secret, data)
that uses a single hash function to expand a secret and seed to an arbitrary length: Pseudo-code (Page 15):P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
HMAC_hash(secret, A(2) + seed) +
HMAC_hash(secret, A(3) + seed) + ...where + indicates concatenation.
A()
is defined as:A(0) = seed
A(i) = HMAC_hash(secret, A(i-1))P_hash
is iterated as many times as necessary to produce the required length. The example given in the RFC is ifP_SHA256
is being used to create 80 bytes, it will be iterated three times (throughA(3)
), creating 96 bytes of data where the last 16 bytes of the final iteration is discarded to leave the needed 80 bytes. The PRF is created by applyingP_hash
to the secret as follows:PRF(secret, label, seed) = P_(secret, label + seed)
I've defined the two functions (
PRF
&P_hash
) but added two additional parameters; the first ifreqLength
to set the output length andHmacLength
which is an enum that will restrict the allowed hash function to SHA256, SHA384, or SHA512. The code that follows I believe follows the RFC correctly, however I feel it is inefficient because of how I'm going back and forth betweenList(Of Byte)
andByte()
's, but I can't figure out how to simplify it; possibly because I've been programming all day or maybe because it is 1:30 AM. Either way I was hoping that someone could help simplify the code because everything I tried (like eliminating some of the loops) resulted in the code not compiling for various reasons. The code I have so far is this:Public Class PRF
Public Enum P\_SHA HMAC\_256 HMAC\_384 HMAC\_512 End Enu