SHA2_Hmac is a keyed-hash function that provides message
authentication using the HMAC algorithm and the SHA-256 hash function.
Public Declare Function SHA2_Hmac Lib "diCryptoSys.dll"
(ByVal strDigest As String, ByRef abData As Byte, ByVal nDataLen As Long,
ByRef abKey As Byte, ByVal nKeyLen As Long) As Long
nRet = SHA2_Hmac(strDigest, abData(0), nDataLen, abKey(0), nKeyLen)
String variable of sufficient length to
receive the message digest in hex format.Byte array containing the text of the message.Long containing the number of bytes in the arrayByte array containing the key.Long containing the number of bytes in the key
long _stdcall SHA2_Hmac(char *strDigest,
const unsigned char *textBytes, long textLen,
const unsigned char *keyBytes, long keyLen);
Long: If successful, the return value is 0;
otherwise it returns a non-zero error code.
Sha256.Hmac Method (Byte[], Byte[])
strDigest must be at least 64 (API_MAX_SHA2_CHARS) characters long (65 in a C program). Note the (0) in abData(0) and abKey(0).
This example reproduces the three test vectors from RFC 2014 using SHA-256 instead of MD5. Note that the results will be different from those given in RFC 2104 because a different hash function is used (RFC 2104 uses MD5).
Dim nRet As Long
Dim abData() As Byte
Dim abKey() As Byte
Dim i As Integer
Dim nDataLen As Long, nKeyLen As Long
Dim strDigest As String * 64
' Test No 1.
' Set key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
ReDim abKey(15)
For i = 0 To 15
abKey(i) = &HB
Next
' Convert string to byte array
abData() = StrConv("Hi There", vbFromUnicode)
nDataLen = UBound(abData) + 1
' Create HMAC digest
nRet = SHA2_Hmac(strDigest, abData(0), nDataLen, abKey(0), 16)
Debug.Print 1; nRet; strDigest
' Test No 2.
abKey() = StrConv("Jefe", vbFromUnicode)
nKeyLen = UBound(abKey) + 1
abData() = StrConv("what do ya want for nothing?", vbFromUnicode)
nDataLen = UBound(abData) + 1
nRet = SHA2_Hmac(strDigest, abData(0), nDataLen, abKey(0), nKeyLen)
Debug.Print 2; nRet; strDigest
' Test No 3.
ReDim abKey(15)
For i = 0 To 15
abKey(i) = &HAA
Next
ReDim abData(49)
For i = 0 To 49
abData(i) = &HDD
Next
nRet = SHA2_Hmac(strDigest, abData(0), 50, abKey(0), 16)
Debug.Print 3; nRet; strDigest
This should result in output as follows:
1 0 492ce020fe2534a5789dc3848806c78f4f6711397f08e7e7a12ca5a4483c8aa6 2 0 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843 3 0 7dda3cc169743a6484649f94f0eda0f9f2ff496a9733fb796ed5adb40a44c3c1