Using CryptoSys API with Microsoft Excel


Question:

I am trying to use the AES256_Hex function in an Excel spreadsheet but I keep getting an error. I expect to see the encrypted hex string in cell C5, but I keep getting error code 125 = Input data too short (TOO_SHORT_ERROR). What am I doing wrong? Trying to use AES256_Hex directly

Answer:

You cannot call the CryptoSys API functions directly from Excel like you have done. The output string needs to be pre-dimensioned to receive the output (and, in Excel, you should check for empty cells). You have to use a macro function.

In your Excel workbook add a new module (Alt+F11, then Insert > Module) with the VBA code below. This adds a new function Udf_AES256_Hex_Encrypt that wraps around the core AES256_Hex function and returns a proper string suitable for use in Excel. Example file made with Excel 2003: AES256.xls (zipped 11 kB).

Using a user-defined function

Option Explicit

' These declarations are copied from basCryptoSys.bas
' (Alternatively, include the entire file as separate Module)
Public Const ENCRYPT As Boolean = True
Public Const DECRYPT As Boolean = False
Public Declare Function AES256_Hex Lib "diCryptoSys.dll" _
    (ByVal strOutput As String, ByVal strInput As String, _
    ByVal strHexKey As String, ByVal bEncrypt As Long) As Long

Function Udf_Aes256_Hex_Encrypt(vntHexInput As Variant, vntHexKey As Variant) As String
    Dim strOutput As String
    Dim strHexInput As String
    Dim strHexKey As String
    Dim nRet As Long
    ' Use variants to cope with empty cells
    If IsEmpty(vntHexInput) Or IsEmpty(vntHexKey) Then
        Exit Function
    End If
    ' Then convert to proper strings
    strHexInput = CStr(vntHexInput)
    strHexKey = CStr(vntHexKey)
    ' Pre-dimension output string
    strOutput = String(Len(strHexInput), " ")
    ' Now call the CryptoSys API function
    nRet = AES256_Hex(strOutput, strHexInput, strHexKey, ENCRYPT)
    ' Return string value
    If nRet = 0 Then
        Udf_Aes256_Hex_Encrypt = strOutput
    Else
        Udf_Aes256_Hex_Encrypt = ""
    End If
End Function

Remarks

This example uses AES-256. In our opinion, using AES-256 is overkill. Just because it's the strongest on the menu, it doesn't mean you have to use it. AES-128 should provide perfectly adequate security. There are some recently-discovered weaknesses in AES-256 not present in the 128-bit version.

Contact

For more information or to comment on this page, please send us a message.

This page last updated 27 October 2011