I have created the below code and I am getting a run time error listed above in the title. I have consulted another article on this error below, however it does not appear to help with the issue. I cannot understand why it works for the first function, but fails on the 2nd. Does anyone have any ideas?
I am using Microsoft Access in VBA.
Reference here
Function EncryptData(StrInput As String, StrKey As String) As String
Dim ObjAES As Object
Dim ObjText As Object
Dim inputBytes() As Byte
Dim keyBytes() As Byte
Dim encryptedBytes() As Byte
Dim i As Integer
Dim encryptedString As String
' Create objects for encryption
Set ObjAES = CreateObject("System.Security.Cryptography.AesManaged")
Set ObjText = CreateObject("System.Text.UTF8Encoding")
' Convert input and key to bytes
inputBytes = ObjText.GetBytes_4(StrInput)
keyBytes = ObjText.GetBytes_4(StrKey)
' Ensure keylength matches AES requirements (16/24/32 bytes)
If UBound(keyBytes) < 15 Then ReDim Preserve keyBytes(15)
If UBound(keyBytes) > 15 Then ReDim Preserve keyBytes(15)
' Perform encryption
ObjAES.Key = keyBytes
ObjAES.Mode = 1 'CBC Mode
encryptedBytes = ObjAES.CreateEncryptor.TransformFinalBlock(inputBytes, 0, UBound(inputBytes) + 1)
' Convert encrypted bytes to base64 string
For i = LBound(encryptedBytes) To UBound(encryptedBytes)
encryptedString = encryptedString & Chr(encryptedBytes(i))
Next i
EncryptedData = encryptedString
End Function
Function DecryptData(StrInput As String, StrKey As String) As String
Dim ObjAES As Object
Dim ObjText As Object
Dim encryptedBytes() As Byte
Dim keyBytes() As Byte
Dim decryptedBytes() As Byte
Dim i As Integer
Dim decryptedString As String
' Create objects for decryption
Set ObjAES = CreateObject("System.Security.Cryptography.AesManaged") 'This is the line of code highlighted when running.
Set ObjText = CreateObject("System.Text.UTF8Encoding")
' Convert input and keys to bytes
encryptedBytes = ojbText.GetBytes_4(StrInput)
keyBytes = ObjText.GetBytes_4(StrKey)
' Ensure key length matches AES requirements (16/24/32 bytes)
If UBound(keyBytes) < 15 Then ReDim Preserve keyBytes(15)
If UBound(keyBytes) > 15 Then ReDim Preserve keyBytes(15)
' Perform decryption
ObjAES.Key = keyBytes
ObjAES.Mode = 1 'CBC Mode
encryptedBytes = ObjAES.CreateEncryptor.TransformFinalBlock(encryptedBytes, 0, UBound(encryptedBytes) + 1)
' Convert encrypted bytes to base64 string
For i = LBound(decryptedBytes) To UBound(decryptedBytes)
decryptedString = decryptedString & Chr(decryptedBytes(i))
Next i
DecryptedData = decryptedString
End Function