Encrypts or decrypts an array of Bytes using a specified mode. The key and IV data are in byte arrays.
Public Declare Function AES256_BytesMode Lib "diCryptoSys.dll"
(ByRef lpOutput As Byte, ByRef lpData As Byte, ByVal nDataLen As Long, ByRef lpKey As Byte,
ByVal bEncrypt As Boolean,
ByVal strMode As String, ByRef lpInitV As Byte) As Long
nRet = AES256_Bytes(lpOutput(0), abData(0), nDataLen, abKey(0), bEncrypt, strMode, abInitV(0))
' Note the "(0)" after the byte array parameters
long __stdcall AES256_BytesMode(unsigned char *lpOutput, const unsigned char *lpInput, long nBytes, const unsigned char *lpKey, int fEncrypt, const char *szMode, const unsigned char *lpIV);
If successful, the return value is 0; otherwise it returns a non-zero error code.
Aes256.Encrypt Method (Byte[], Byte[], Mode, Byte[])
Aes256.Decrypt Method (Byte[], Byte[], Mode, Byte[])
The input array lpData
must be a multiple of the block size of 16 bytes long.
If not, an error code will be returned.
The key array abKey()
must be exactly 32 bytes long (i.e. 256 bits).
The initialization vector abInitV()
must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use 0
).
The output array lpOutput must be at least as long as the input array.
lpOutput and lpData may be the same.
Dim nRet As Long Dim strOutput As String Dim strInput As String Dim sCorrect As String Dim abKey() As Byte Dim abInitV() As Byte Dim abResult() As Byte Dim abData() As Byte Dim nDataLen As Long ' Set up input in byte arrays strInput = "Now is the time for all good men" sCorrect = "36161E5B4B62401A5B57996F7D6839D34E181930DEBBAEBE84AE01139E9581A6" abKey = _ cnvBytesFromHexStr("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f") abInitV = cnvBytesFromHexStr("FEDCBA9876543210FEDCBA9876543210") abData = StrConv(strInput, vbFromUnicode) nDataLen = UBound(abData) - LBound(abData) + 1 ' Pre-dimension output array ReDim abResult(nDataLen - 1) Debug.Print "KY=" & cnvHexStrFromBytes(abKey) Debug.Print "IV=" & cnvHexStrFromBytes(abInitV) Debug.Print "PT=" & cnvHexStrFromBytes(abData) ' Encrypt in one-off process nRet = AES256_BytesMode(abResult(0), abData(0), nDataLen, abKey(0), _ ENCRYPT, "CBC", abInitV(0)) Debug.Print "CT=" & cnvHexStrFromBytes(abResult) Debug.Print "OK=" & sCorrect Debug.Assert (sCorrect = cnvHexStrFromBytes(abResult)) ' Now decrypt back nRet = AES256_BytesMode(abData(0), abResult(0), nDataLen, abKey(0), _ DECRYPT, "CBC", abInitV(0)) strOutput = StrConv(abData(), vbUnicode) Debug.Print "P'=" & strOutput ' Check Debug.Assert (strOutput = strInput)
This should result in output as follows:
KY=000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F IV=FEDCBA9876543210FEDCBA9876543210 PT=4E6F77206973207468652074696D6520666F7220616C6C20676F6F64206D656E CT=36161E5B4B62401A5B57996F7D6839D34E181930DEBBAEBE84AE01139E9581A6 OK=36161E5B4B62401A5B57996F7D6839D34E181930DEBBAEBE84AE01139E9581A6 P'=Now is the time for all good men