I thought that adding HMAC support to my TLS simulation program would be relatively straight forward, but I was wrong. It is not as simple as adding a Hash to each record before encryption, as in SSL. HMAC uses a Symmetric Key to hash the record string according to the following formula:
'HMAC_MD5(Key, m) = MD5((Key XOR opad) ++ MD5((Key XOR ipad) ++ m)
'(++ means concatenate, "opad" is the bytes "5c 5c ... 5c",
'and "ipad" is the bytes "36 36 ... 36").
I came up with the following code:
Everthing works, except I can't get the MAC codes to match:
I have tried every combination I can think of, but they never compare, and I am at a loss to figure out how to debug this code. Any help would be much appreciated. The full code is available in the CodeBank.
http://www.vbforums.com/showthread.p...LS1-Simulation
J.A Coutts
'HMAC_MD5(Key, m) = MD5((Key XOR opad) ++ MD5((Key XOR ipad) ++ m)
'(++ means concatenate, "opad" is the bytes "5c 5c ... 5c",
'and "ipad" is the bytes "36 36 ... 36").
I came up with the following code:
Code:
Public Function HMAC_MD5(ByVal hHMAC As Long, ByVal strInput As String) As String
Dim strHash As String
Dim hMACHash As Long
Dim lLen As Long
Dim HMACInfo As HMAC_INFO
'if inner & outer strings and lengths set to 0, defaults are used
'They should already be zeroed, but to make sure
ZeroMemory HMACInfo.ALG_ID, Len(HMACInfo)
HMACInfo.ALG_ID = CALG_MD5
If CryptCreateHash(hCryptProv, CALG_HMAC, hHMAC, 0, hMACHash) = 0 Then _
Err.Raise Err.LastDllError, , "Could not get create hash (CryptCreateHash API)"
If CryptSetHashParam(hMACHash, HP_HMAC_INFO, HMACInfo, 0) = 0 Then _
Err.Raise Err.LastDllError, , "Could not set Hash Parameters (CryptSetHashParam API)"
If CryptHashData(hMACHash, strInput, Len(strInput), 0) = 0 Then _
Err.Raise Err.LastDllError, , "Could not Hash Data(CryptHashData API)"
If CryptGetHashParam(hMACHash, HP_HASHVAL, vbNullString, lLen, 0) = 0 Then _
Err.Raise Err.LastDllError, , "Could not get hash length(CryptGetHashParam API)"
strHash = String$(lLen, Chr$(0))
If CryptGetHashParam(hMACHash, HP_HASHVAL, strHash, lLen, 0) = 0 Then _
Err.Raise Err.LastDllError, , "Could not recover HMAC hash(CryptGetHashParam API)"
If hMACHash <> 0 Then CryptDestroyHash hMACHash
HMAC_MD5 = strHash
End Function
Code:
Private Function VerifyHMAC(ByRef DecryptedRecord As String) As Boolean
'Verify the Message Authentication Code
Dim AppendedHMAC As String
Dim CalculatedHMAC As String
Dim lLen As Long
lLen = Len(DecryptedRecord) - 16
AppendedHMAC = Mid(DecryptedRecord, lLen)
DecryptedRecord = Mid(DecryptedRecord, 1, lLen)
CalculatedHMAC = HMAC_MD5(hReadMAC, DecryptedRecord)
If CalculatedHMAC = AppendedHMAC Then
VerifyHMAC = True
Else
VerifyHMAC = False
End If
End Function
http://www.vbforums.com/showthread.p...LS1-Simulation
J.A Coutts