CryptoSys Home > API > Using CryptoSys API with Microsoft Excel

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

Changed in v5.1: error code will now be 26 = Data not a valid length (BAD_LENGTH_ERROR)

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.

Using a user-defined function

Here is example file made with Excel 2003: AES256.xls (zipped 11 kB). 2017-03-23: Updated with VB7 conditional for 64-bit Office and a more useful error message.

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
#If VB7 Then
Public Declare PtrSafe Function AES256_Hex Lib "diCryptoSys.dll" _
    (ByVal strOutput As String, ByVal strInput As String, _
    ByVal strHexKey As String, ByVal bEncrypt As Long) As Long
#Else
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
#End If

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 = "**ERROR " & nRet
    End If
End Function

Contact

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

This page last updated 15 August 2025.