Sample - AESEncode to Base64 to AESDecode

Just starting out? Need help? Post your questions and find answers here.
dfmurray99
New User
New User
Posts: 3
Joined: Tue Dec 08, 2009 10:55 pm

Sample - AESEncode to Base64 to AESDecode

Post by dfmurray99 »

For you pro's out there, this is probably trivial, but I thought it may help others if I post my code to write AES encrypted data to a database.
Since the encrypted data may contain ASCII 0's, one can't use a string.
I've use base64 to get around that. Thinking having all the parts in one example may help someone else.
It took me a while to get the pointers all working correctly.




;
; Encrypt 'AMessage' using 'Key' into memory at '*EncryptMem', probably will contain some bytes with value zero
; Base64Encode '*EncryptMem' into string 'B64String', this will contain no zero bytes
;
; 'B64String' can now be written to database
;
; Read 'B64String' from database
;
; Base64Decode 'B64String' into memory at '*RecoverMem'
; Decrypt '*RecoverMem' using 'Key' into memory at '*DecryptMem'
; PeekS to get 'BMessage' from '*DecryptMem'
;


Key.s = "a7klc2ag7fa6sf23ucd093"


AMessage.s = "01234567890123456789" ; AMessage size is 20 bytes
*EncryptMem = AllocateMemory(20+1) ; Space for the string and it's null terminating character (ASCII mode)
B64String.s = Space(99) ; Should only need 27 bytes (20 + 33%) but docs say to use 64 byte minimum
*RecoverMem = AllocateMemory(20+1)
*DecryptMem = AllocateMemory(20+1)
BMessage.s = Space(20)


; AMessage encrypted into memory at EncryptMem
AESEncoder(@AMessage, *EncryptMem, 20, @Key, 128, 0, #PB_Cipher_ECB)

; memory at EncryptMem Base64Encoded into string B64String.... Can be written to database
Base64Encoder(*EncryptMem, MemorySize(*EncryptMem), @B64String, 99)



; for demonstration purposes, simulate writing then reading data to/from database
; write B64String To database
DataBaseField$ = Trim(B64String)

; read B64String from database
B64String = DataBaseField$


; string B64String Base64Decoded into memory at RecoverMem
Base64Decoder(@B64String, StringByteLength(B64String), *RecoverMem, 99)


; memory at RecoverMem decrypted into memory at DecryptMem
AESDecoder(*RecoverMem, *DecryptMem, 20, @Key, 128, 0, #PB_Cipher_ECB)


; memory at DecryptMem put into string BMessage
BMessage = PeekS(*DecryptMem)



Debug "B64String = " + B64String
Debug "AMessage = " + AMessage
Debug "BMessage = " + BMessage