Page 1 of 1

Crypting with the AES lib?

Posted: Sun Oct 02, 2005 1:42 am
by roachofdeath
Hello,

Well, after 4 or so hours scortching the forum looking for a way to encrypt and decrypt with Sec's AES lib, I came out with this code:

Code: Select all

Procedure AES_Crypt_File(Mode, InFilename.s, OutFileName.s, key.s, FileReadBufferSize)
    ;Mode 0 = Encrypt
    ;Mode 1 = Decrypt
    If FileReadBufferSize % 16 = 0
        #OutFile  = 0
        #InFile   = 1
        If Mode = 0
            packed_filename.s = InFilename + ".pack"
            res = CreatePack(packed_filename)
            If res <> 0
                res = AddPackFile(InFilename , 9)
                ClosePack()
            Else
                MessageRequester(#title,"Error!")
                ProcedureReturn
            EndIf
            InFilename = packed_filename
        EndIf
        FileIn=OpenFile(#InFile,InFilename.s)
        If FileIn<>0
            *KeyBuffer = AllocateMemory(32)
            key = key + key
            j=-1
            For i=1 To Len(key) Step 2
                j=j+1
                PokeB(*KeyBuffer+j,hex2dec(Mid(key,i,2)))     
            Next i
            AES256Init(*KeyBuffer)
            *InputBuffer = AllocateMemory(FileReadBufferSize)
            *OutputBuffer = AllocateMemory(FileReadBufferSize)
            *PlainBlock = AllocateMemory(16)
            *EncryptionBlock = AllocateMemory(16)
            FileLength = FileSize(InFilename)
            BlocksToRead = Int(FileLength/FileReadBufferSize)
            Result=CreateFile(#OutFile,OutFileName)
            If Result
                For Offset = 0 To BlocksToRead
                    If Offset<BlocksToRead
                        BlockSize = FileReadBufferSize
                    Else
                        BlockSize = FileLength-Offset*FileReadBufferSize
                    EndIf         
                    UseFile(1)
                    FileSeek(Offset*FileReadBufferSize)
                    Result=ReadData(*InputBuffer,BlockSize)
                    If BlockSize<>FileReadBufferSize And Mode = 0         
                        PadBytes = (FileReadBufferSize - BlockSize) % 16
                        For i=0 To PadBytes-1
                            PokeB(*InputBuffer+BlockSize+i,PadBytes)
                        Next i
                        BlockSize = BlockSize + PadBytes
                    EndIf
                    UseFile(0)
                    For  EncryptionBlockOffset = 0 To FileReadBufferSize / 16
                        CopyMemory(*InputBuffer+EncryptionBlockOffset*16, *PlainBlock , 16)
                        If Mode = 0         
                            *EncryptionBlock = AES256Encrypt(*PlainBlock)
                        ElseIf Mode = 1
                            *EncryptionBlock = AES256Decrypt(*PlainBlock)
                        EndIf
                        CopyMemory(*EncryptionBlock,*OutputBuffer+EncryptionBlockOffset*16,16)
                    Next EncryptionBlockOffset
                    FileSeek(Offset*FileReadBufferSize)
                    If Mode=1 And ((Offset = BlocksToRead) Or (FileLength % FileReadBufferSize = 0))
                        PaddedBytes=PeekB(*OutputBuffer+BlockSize-1)  & $FF
                        For i=1 To PaddedBytes
                            If PeekB(*OutputBuffer+BlockSize-i)<>PaddedBytes
                                Break               
                            EndIf
                        Next i
                        If i>PaddedBytes And PaddedBytes<16
                            BlockSize=BlockSize-PaddedBytes
                        EndIf
                    EndIf
                    WriteData(*OutputBuffer,BlockSize)
                Next Offset
                CloseFile(#InFile)
                CloseFile(#OutFile)
                If Mode = 1
                    packed_filename.s = OutFileName
                    res = OpenPack(packed_filename)
                    If res <> 0
                        *addr = NextPackFile()
                        size = PackFileSize()
                        File = OpenFile(#InFile, packed_filename + ".dec")
                        WriteData(*addr, size)
                        CloseFile(#InFile)
                        ClosePack()
                    Else
                        MessageRequester(#title,"Error!")
                        ProcedureReturn
                    EndIf
                EndIf
               
            EndIf
            FreeMemory(-1)
        EndIf
    Else
        Error = 1
    EndIf
EndProcedure 
I successfully used it to encrypt a file, but I have not yet been able to decrypt the file. Any ideas on what is going wrong?

This is the code I am using to call it:

Code: Select all

AES_Crypt_File(type.l,file$,file$,key$, 8192*2)
(file$ = "C:\prog.exe", key$="TheKey")

Posted: Wed Oct 05, 2005 7:13 pm
by Straker
Hmmm. I use a derivitive of this function all the time.

Are you trying:

Code: Select all

lInFile.s = "C:\prog.exe"
lOutFile.s = "C:\prog.exe.enc"
lKey.s = "TheKey"

; to encrypt
AES_Crypt_File ( 0, lInFile.s, lOutFile.s, lKey.s, 8192*2 )

; to decrypt
AES_Crypt_File ( 1, lOutFile.s, lInFile.s, lKey.s, 8192*2 )
?

Posted: Wed Oct 05, 2005 8:52 pm
by roachofdeath
It encrypts fine, but it's the decyrpting it's having trouble with. I select the .aes (that's what I have the ecnrypted name as) and it makes a new one like "file.exe.aes.exe"... the encrypted was called "file.exe.aes"... the original file was called "file.exe"

Even after i change the decrypted to "file.exe" it still says it's not a win32 application

EDIT: I took a look at the encrypted version, and relaized, its just an empty file..

Posted: Wed Oct 05, 2005 9:15 pm
by Straker
Make sure you have the latest AES lib. I found a google cache of the page where I got my AES lib:

http://66.102.7.104/search?q=cache:lmWj ... o.fr&hl=en

Click on the first AES link to download the library and put in your UserLibraries folder, then check out the sample code page here: http://perso.wanadoo.fr/jugesoftware/pu ... tionSEC.pb

Posted: Thu Oct 06, 2005 11:50 pm
by roachofdeath
I have the lastest version... maybe is there an example for this lib? ;)

Posted: Sun Oct 09, 2005 2:50 am
by Straker
This is not mine but copied from the sample page:

Code: Select all

;- ORIGINAL CODE from Max.² modified by 'newbie' to works with Sec's AES LIB v2
;- compression has been added. The file is now packed, and then encrypted.

;Procedure by PB / english forum
Procedure.l hex2dec(h$)
    h$=UCase(h$)
    For r=1 To Len(h$)
        d<<4 : a$=Mid(h$,r,1)
        If Asc(a$)>60
            d+Asc(a$)-55
        Else
            d+Asc(a$)-48
        EndIf
    Next
    ProcedureReturn d
    
EndProcedure

Procedure AES_Crypt_File(Mode, InFilename.s, OutFileName.s, key.s, FileReadBufferSize)
    
    ;Mode 0 = Encrypt
    ;Mode 1 = Decrypt
    
    If FileReadBufferSize % 16 = 0
        #OutFile  = 0
        #InFile   = 1
        
        If Mode = 0
            packed_filename.s = InFilename + ".pack"
            res = CreatePack(packed_filename)
            If res <> 0
                ; 9 = MAX compression
                res = AddPackFile(InFilename , 9)
                ClosePack()
            Else
                Debug "error while packing"
                ProcedureReturn
            EndIf
            InFilename = packed_filename
        EndIf
        
        
        FileIn=OpenFile(#InFile,InFilename.s)
        If FileIn<>0
            ;Key transformation
            *KeyBuffer = AllocateMemory(32)
            key = key + key ; key is a MD5 128 bits key, we need 256 bits for AES 256, it's a workaround until we have SHA-256
            Debug "key = " + key
            j=-1
            For i=1 To Len(key) Step 2
                j=j+1
                PokeB(*KeyBuffer+j,hex2dec(Mid(key,i,2)))     
            Next i
            
            AES256Init(*KeyBuffer)
            
            *InputBuffer = AllocateMemory(FileReadBufferSize)
            *OutputBuffer = AllocateMemory(FileReadBufferSize)
            *PlainBlock = AllocateMemory(16)
            *EncryptionBlock = AllocateMemory(16)
            
            FileLength = FileSize(InFilename)
            BlocksToRead = Int(FileLength/FileReadBufferSize)
            
            Result=CreateFile(#OutFile,OutFileName)
            If Result
                For Offset = 0 To BlocksToRead
                    If Offset<BlocksToRead
                        BlockSize = FileReadBufferSize
                    Else
                        BlockSize = FileLength-Offset*FileReadBufferSize
                    EndIf         
                    ; get data from input file
                    UseFile(1)
                    FileSeek(Offset*FileReadBufferSize)
                    Result=ReadData(*InputBuffer,BlockSize)
                    
                    ;Pad (make multiple of 16bytes) if needed
                    If BlockSize<>FileReadBufferSize And Mode = 0         
                        Debug "Pad!"
                        PadBytes = (FileReadBufferSize - BlockSize) % 16
                        Debug "Need to pad with "+Str(PadBytes)+" bytes"
                        For i=0 To PadBytes-1
                            ;Using pad method RFC2630
                            PokeB(*InputBuffer+BlockSize+i,PadBytes)
                        Next i
                        BlockSize = BlockSize + PadBytes
                    EndIf
                    
                    ; write data to outputfile
                    UseFile(0)
                    For  EncryptionBlockOffset = 0 To FileReadBufferSize / 16
                        CopyMemory(*InputBuffer+EncryptionBlockOffset*16, *PlainBlock , 16)
                        If Mode = 0         
                            *EncryptionBlock = AES256Encrypt(*PlainBlock)
                        ElseIf Mode = 1
                            *EncryptionBlock = AES256Decrypt(*PlainBlock)
                        EndIf
                        CopyMemory(*EncryptionBlock,*OutputBuffer+EncryptionBlockOffset*16,16)
                    Next EncryptionBlockOffset
                    FileSeek(Offset*FileReadBufferSize)
                    ;Strip padded bytes
                    If Mode=1 And ((Offset = BlocksToRead) Or (FileLength % FileReadBufferSize = 0))
                        
                        
                        Debug "Unpad!"
                        PaddedBytes=PeekB(*OutputBuffer+BlockSize-1)  & $FF
                        Debug "Supposed # of padded bytes: "+Str(PaddedBytes)
                        For i=1 To PaddedBytes
                            If PeekB(*OutputBuffer+BlockSize-i)<>PaddedBytes
                                Debug "False alarm. No unpadding needed."
                                Break               
                            EndIf
                        Next i
                        If i>PaddedBytes And PaddedBytes<16
                            BlockSize=BlockSize-PaddedBytes
                            Debug "Decreasing Block by "+Str(PaddedBytes)+" to get rid of padded bytes"
                        EndIf
                    EndIf
                    WriteData(*OutputBuffer,BlockSize)
                Next Offset
                CloseFile(#InFile)
                CloseFile(#OutFile)
                If Mode = 1
                    packed_filename.s = OutFileName
                    res = OpenPack(packed_filename)
                    If res <> 0
                        *addr = NextPackFile()
                        size = PackFileSize()
                        File = OpenFile(#InFile, packed_filename + ".dec")
                        WriteData(*addr, size)
                        CloseFile(#InFile)
                        ClosePack()
                    Else
                        Debug "error while unpacking"
                        ProcedureReturn
                    EndIf
                EndIf
                
            EndIf
            FreeMemory(-1)
        EndIf
    Else
        Error = 1
    EndIf
    
EndProcedure

start = GetTickCount_()

key.s = MD5Fingerprint("toto", 4)
InFile.s = "c:\alg.exe"
EncryptFile.s = "c:\alg.enc"
DecryptFile.s = "c:\alg.dec.exe"

AES_Crypt_File(0, InFile, EncryptFile, key, 8192*2)
AES_Crypt_File(1, EncryptFile, DecryptFile, key, 8192*2)
DeleteFile(DecryptFile)
RenameFile(DecryptFile + ".dec", DecryptFile)
Debug "Milliseconds: "+Str(GetTickCount_()-start)
If MD5FileFingerprint(InFile) = MD5FileFingerprint(DecryptFile)
    Debug "ok"
Else
    Debug "error"
EndIf