UnderwareDESIGN

PlayBASIC => Resources => Source Codes => Topic started by: kevin on April 15, 2015, 12:59:36 PM

Title: Encode Files / Hide File Contents / Xor Encryption
Post by: kevin on April 15, 2015, 12:59:36 PM
  Encode File  / Hide File Contents / Xor Encryption

     This example loads a file into a memory bank,  XOR'S the bank and saves the result back to disc.   Rather than running through and xor'ing each byte/long, we're using some built in functionality to do the heavy lifting for us, by copying the file data in chunks directly into an FX image fragment, then using the XOR inkmode to do the work.   So the amount of runtime overhead is tiny.  


[pbcode]

   explicit on

   // the image you want to test..  point this at some junk picture file
   local srcfile$      ="SOME PICTURE.png"

   // the encoded output file
   local encodedfile$=replace$(srcfile$,".","-ENCODED-FILE.")

   // the decoded output file
   local resultfile$=replace$(srcfile$,".","-DECODED-FILE.")


   // load the source file and XOR it the
   EncodeFile(Srcfile$,encodedfile$,$33445522)


   // we decode using the same function and the same key
   EncodeFile(encodedfile$,resultfile$,$33445522)


   // load the final image
   loadimage resultfile$,1
   drawimage  1,0,50,false


   Sync
   waitkey




;*=-----------------------------------------------------------------------------=*   
;                               >> XOR Encode File <<
;*=-----------------------------------------------------------------------------=*   
;
;  This function XORS the input file and saves the result out to disc.
;
;*=-----------------------------------------------------------------------------=*   





function EncodeFile(Srcfile$,DestFile$,XORKEY)

      if fileexist(SrcFIle$)

         print "encoding:"+srcfile$
      
            local Size=Filesize(SrcFIle$)
            local ThisBank=NewBank(Size)

            local fh=readnewfile(Srcfile$)
            if fh
                  local ptr =GetBankPtr(ThisBank)
                  Readmemory fh,ptr,Size
                  closefile fh

                  XorBank(ThisBank,XORKEY)

                  if lower$(srcfile$)<> lower$(DestFile$)
                     if fileexist(destFile$) then deletefile destfile$
                  
                     local fh=writenewfile(Destfile$)
                     if fh
                           Writememory  fh,ptr,ptr+Size
                           closefile fh
                     endif
                  endif   

            endif


            deletebank thisbank

      endif


EndFUnction



;*=-----------------------------------------------------------------------------=*   
;                                   >> XOR BANK <<
;*=-----------------------------------------------------------------------------=*   
;
;  This function XORS the contents of the memory bank with a user defiend 32bit
; key.  This function uses PlayBASIC XOR draw mode to do the heavy lifting, making
; the function vey fast.
;
;*=-----------------------------------------------------------------------------=*   


function XorBank(ThisBank,ThisKEY)

      if GetBankStatus(ThisBank)
         local size=getbanksize(ThisBank)
      
                  local oldsurface=getsurface()
                  local oldinkmode =getinkmode()

                  local StripWidth=1024
                  local StripHeight=32

                  // first we create an FX buffer that's 32bit
                  local StripImage=GetFreeIMage()
                  CReateFXImageEX StripImage,StripWidth,StripHeight,32

                  rendertoimage StripImage

                  local Modulo=GetIMagePitch(StripIMage)
                  local BytesPerChunk=Modulo*StripHeight
                  

                  local stripptr=getimagePtr(StripImage)

                  local lp

                  // set to XOR mode
                  inkmode 1+1024
                  
                  local SrcPtr=GetBankPtr(ThisBank)                  
                  for lp=0 to size-1 step BytesPerChunk
                  
                        local ChunkSize=BytesPerChunk
                        if lp+BytesPerChunk>=Size
                              ChunkSize=Size-lp
                        endif
               
                        // copy this chunk of bytes into the image buffer directly   
                        copymemory SrcPtr,StripPtr,ChunkSize

                        // draw box over the image in XOR mode using this INK colour as the KEY
                        boxc 0,0,StripWidth,StripHeight,true,ThisKEY                        

                        // copy this chunk of bytes into the image   
                        copymemory StripPtr,SrcPtr,ChunkSize
            
                        // move the pointer to the next chunk along in the bank
                        SrcPtr+=BytesPerChunk
                        
                  next

                  rendertoimage oldsurface
                  inkmode oldinkmode

                  deleteimage Stripimage

      endif
      
EndFunction

[/pbcode]
Title: Re: Encode Files / Hide File Contents / Xor Encryption
Post by: kevin on April 21, 2015, 01:28:03 AM
 Encode File  / Hide File Contents / Xor Encryption #2 - Loading Encrypted Images From Memory

     This example expands upon the previous example, breaking up some of the previous code and creating a load from memory function.   PlayBASIC supports loading various images types of memory including BMP / TGA / PNG all except JPG at this point.  To load a image from memory through the LoadImage functions we give the function the address (as a string) of the image in memory rather than a filename.   The loader expects the pointer you give it to be pointing at the size of the image chunk.  Which is necessary given how some of the image loaders.   Anyway,  when loading from memory the loading streams through the memory as if it was a coming from disc.      This means we can encode our images in some way (here were using XOR) then wrap up the image loading functions to apply what ever decoding is required, without ever having to write the decoded file back to disc..  Making it a more secure what dealing with your media assets..  


[pbcode]

   explicit on

   // the image you want to test..  point this at some junk picture
   local srcfile$="d:\PlayBasicBanner.png"
   
   // create the name of the encoded output file
   local encodedfile$=replace$(srcfile$,".","-ENCODED-FILE.")


   // XOR encode the original file with the user KEY and save it to disc with a new name
   EncodeFile(Srcfile$,encodedfile$,$33445522)


   // Load the encoded version  of the file to Memory, decode it and then load,
   // the image from memory (PNG / BMP / TGA only)
   local ThisImage=LoadEncodedImage(EncodedFIle$,$33445522)
   
   // display the loaded image
   drawimage  ThisImage,0,50,false


   Sync
   waitkey




;*=-----------------------------------------------------------------------------=*   
;                               >> XOR Encode File <<
;*=-----------------------------------------------------------------------------=*   
;
;  This function XORS the input file and saves the result out to disc.
;
;*=-----------------------------------------------------------------------------=*   


function EncodeFile(Srcfile$,DestFile$,XORKEY)

      if fileexist(SrcFIle$)

         print "encoding:"+srcfile$
      
            local Size=Filesize(SrcFIle$)
            local ThisBank=NewBank(Size)

            local fh=readnewfile(Srcfile$)
            if fh
                  local ptr =GetBankPtr(ThisBank)
                  Readmemory fh,ptr,Size
                  closefile fh

                  XorBank(ThisBank,XORKEY)

                  if lower$(srcfile$)<> lower$(DestFile$)
                     if fileexist(destFile$) then deletefile destfile$
                  
                     local fh=writenewfile(Destfile$)
                     if fh
                           Writememory  fh,ptr,ptr+Size
                           closefile fh
                     endif
                  endif   

            endif


            deletebank thisbank

      endif


EndFUnction




;*=-----------------------------------------------------------------------------=*   
;                               >> Load Encoded Image <<
;*=-----------------------------------------------------------------------------=*   
;
;  This function loads the file into memory, restored the data to it's original state
; using the XOR function and the orignal KEY.   Then it loads the file directly from
; memory as an Image.
;
;*=-----------------------------------------------------------------------------=*   



Function LoadEncodedImage(ThisFIle$,ThisKey)

      if fileexist(ThisFIle$)

            print "loading Encoded Image file:"+Thisfile$
      
            local Size=Filesize(ThisFIle$)
            local ThisBank=NewBank(Size+32)

            local fh=readnewfile(Thisfile$)
            if fh
                  local ptr =GetBankPtr(ThisBank)
                  Readmemory fh,ptr+4,Size
                  closefile fh


                  ; poke the size of the image into the head of the bank
                  pokebankint ThisBank,0,size
                  
                  ; unscramble the image memory                  
                  XorMemory(Ptr+4,Size,ThisKEY)

                  ; load it directly from memory
                  ThisImage=loadNEwImage("&"+str$(Ptr))

            endif

            deletebank thisbank

      endif




EndFUnction ThisImage


;*=-----------------------------------------------------------------------------=*   
;                                   >> XOR BANK <<
;*=-----------------------------------------------------------------------------=*   
;
;  This function XORS the contents of the memory bank with a user defiend 32bit
; key.  This function uses PlayBASIC XOR draw mode to do the heavy lifting, making
; the function vey fast.
;
;*=-----------------------------------------------------------------------------=*   


function XorBank(ThisBank,ThisKEY)
      if GetBankStatus(ThisBank)
            XorMemory(getbankptr(ThisBank),getbanksize(ThisBank),ThisKEY)
      endif
      
EndFunction





;*=-----------------------------------------------------------------------------=*   
;                                   >> XOR BANK <<
;*=-----------------------------------------------------------------------------=*   
;
;  This function XOR's a chunk of memory with a 32bit key
;
;*=-----------------------------------------------------------------------------=*   


function XorMemory(SrcPtr,Size,ThisKEY)

      if Srcptr<>0 and Size>0
      
                  local oldsurface=getsurface()
                  local oldinkmode =getinkmode()

                  local StripWidth=1024
                  local StripHeight=32

   
                  // first we create an FX buffer that's 32bit and a power of 2 wide
                  local StripImage=GetFreeIMage()
                  CReateFXImageEX StripImage,StripWidth,StripHeight,32

                  rendertoimage StripImage

                  local Modulo=GetIMagePitch(StripIMage)
                  local BytesPerChunk=Modulo*StripHeight
                  

                  local stripptr=getimagePtr(StripImage)

                  local lp

                  // set to XOR mode
                  inkmode 1+1024
                  
                  for lp=0 to size-1 step BytesPerChunk
                  
                        local ChunkSize=BytesPerChunk
                        if lp+BytesPerChunk>=Size
                              ChunkSize=Size-lp
                        endif
               
                        // copy this chunk of bytes into the image buffer directly   
                        copymemory SrcPtr,StripPtr,ChunkSize

                        // draw box over the image in XOR mode using this INK colour as the KEY
                        boxc 0,0,StripWidth,StripHeight,true,ThisKEY                        

                        // copy this chunk of bytes from the image back into memory
                        copymemory StripPtr,SrcPtr,ChunkSize
            
                        // move the pointer to the next chunk along in the bank
                        SrcPtr+=BytesPerChunk
                        
                  next

                  rendertoimage oldsurface
                  inkmode oldinkmode

                  deleteimage Stripimage

      endif
      
EndFunction

[/pbcode]