Skip to content

Commit c52b72b

Browse files
committed
reuse the key stretching in HMAC for multiple invocations
every time we call a HMAC_SHA256 it needs to create a new instance and calculate the i_key and o_key, even if the key used is the same use one instance of the HMAC and just copy state also use multiple update calls, don't concatenate inputs
1 parent 4ae435a commit c52b72b

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

tlslite/mathtls.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -676,13 +676,22 @@ def paramStrength(param):
676676
return 256 # NIST SP 800-57
677677

678678

679-
def P_hash(macFunc, secret, seed, length):
679+
def P_hash(mac_name, secret, seed, length):
680+
"""Internal method for calculation the PRF in TLS."""
680681
ret = bytearray(length)
682+
seed = compatHMAC(seed)
681683
A = seed
682684
index = 0
685+
mac = hmac.HMAC(compatHMAC(secret), digestmod=mac_name)
683686
while index < length:
684-
A = macFunc(secret, A)
685-
output = macFunc(secret, A + seed)
687+
a_fun = mac.copy()
688+
a_fun.update(A)
689+
A = a_fun.digest()
690+
out_fun = mac.copy()
691+
out_fun.update(A)
692+
out_fun.update(seed)
693+
output = out_fun.digest()
694+
686695
how_many = min(length - index, len(output))
687696
ret[index:index+how_many] = output[:how_many]
688697
index += how_many
@@ -696,8 +705,8 @@ def PRF(secret, label, seed, length):
696705
S2 = secret[ int(math.floor(len(secret)/2.0)) : ]
697706

698707
#Run the left half through P_MD5 and the right half through P_SHA1
699-
p_md5 = P_hash(HMAC_MD5, S1, label + seed, length)
700-
p_sha1 = P_hash(HMAC_SHA1, S2, label + seed, length)
708+
p_md5 = P_hash("md5", S1, label + seed, length)
709+
p_sha1 = P_hash("sha1", S2, label + seed, length)
701710

702711
#XOR the output values and return the result
703712
for x in range(length):
@@ -706,11 +715,11 @@ def PRF(secret, label, seed, length):
706715

707716
def PRF_1_2(secret, label, seed, length):
708717
"""Pseudo Random Function for TLS1.2 ciphers that use SHA256"""
709-
return P_hash(HMAC_SHA256, secret, label + seed, length)
718+
return P_hash("sha256", secret, label + seed, length)
710719

711720
def PRF_1_2_SHA384(secret, label, seed, length):
712721
"""Pseudo Random Function for TLS1.2 ciphers that use SHA384"""
713-
return P_hash(HMAC_SHA384, secret, label + seed, length)
722+
return P_hash("sha384", secret, label + seed, length)
714723

715724
def PRF_SSL(secret, seed, length):
716725
bytes = bytearray(length)

0 commit comments

Comments
 (0)