Jump to content
Jfish

Create Self Extracting Encrypted EXE files

Recommended Posts

Hello all.  I was playing around with encrypt.au3 and thought it would be neat to build an executable that could extract and decrypt an encrypted file (sort of like an option in PGP if you have ever used that before).  I had to think on the issue of installing the file in the exe because you can't use variable path names.  The approach I came up with may not be the best - others may have much better ideas - but I thought I would share it nonetheless in case anyone finds it interesting.

;*********************************************
; Example script
; ENCRYPT A FILE INTO A SELF-EXTRACTING EXE
; by: JFish
;
;********************************************

#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

#include <Crypt.au3> ; will be used for the encryption
#include <File.au3> ; will be used to manipulate au3 file before we compile

#Region ### START Koda GUI section ### Form=C:\Users\RC01712\Documents\Scripts\Encrypt Tool\encrypt_GUI.kxf
$Form1 = GUICreate("Form1", 657, 244, 192, 132)
$sourceInput = GUICtrlCreateInput("", 144, 48, 337, 24)
$sourceBtn = GUICtrlCreateButton("Browse", 40, 48, 89, 25)
$encryptBtn = GUICtrlCreateButton("Encrypt", 224, 128, 145, 33)
$passwordInput = GUICtrlCreateInput("", 144, 80, 337, 24)
$Label1 = GUICtrlCreateLabel("Password", 40, 80, 73, 24)
GUICtrlSetFont(-1, 10, 400, 0, "MS Sans Serif")
$decryptBtn = GUICtrlCreateButton("Decrypt", 224, 176, 145, 33)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

; var declaration for global scope
dim $sourceFile, $password, $filename, $filenameRoot, $fileExtension, $publicEncFileNameFullPath, $publicEncFileName

; select a source file that we want to encrypt
func _selectFile()
    GUICtrlSetData($sourceInput,"")
    $filename=""
    $sourceFile=FileOpenDialog("Please select a file to encrypt",@ScriptDir,"All (*.*)")
    $dirLen=stringlen(@WorkingDir)+1
    ;grab the file name
    $filename=StringTrimLeft($sourceFile,$dirLen)
    local $firstDot=stringinstr($filename,".",0,-1)
    ;grab the file root name without the extension
    $filenameRoot=stringtrimright($filename,stringlen($filename)-$firstDot+1)
    ;grab the file extension
    $fileExtension=stringtrimleft($filename,$firstDot-1)
    ;MsgBox("","",$fileExtension)
    GUICtrlSetData($sourceInput,$sourceFile)
EndFunc

func _encrypt()
$password = GUICtrlRead($passwordInput)
if $password="" then
    MsgBox("","","please enter a password")
EndIf
; encrypt the file NOTE: method in example of AES 256 is hard coded
$result =_Crypt_EncryptFile($sourceFile,@ScriptDir&"\"&$filenameRoot&"_enc"&$fileExtension,$password,$CALG_AES_256)
; if the encryptions works ...
    if $result=True Then
        ; set the full path name to the file including the new "_enc" showing that it is encrypted
        $publicEncFileNameFullPath=@ScriptDir&"\"&$filenameRoot&"_enc"&$fileExtension
        ; setr the name of the encrypted file without the path
        $publicEncFileName=$filenameRoot&"_enc"&$fileExtension
        ; call the function to create the exe
        _createEXE($publicEncFileName,$publicEncFileName)
    else
        MsgBox("","","encryption error")
    EndIf
MsgBox("","Encrypt status",$result)
EndFunc


func _createEXE($publicEncFileNameFullPath,$publicEncFileName)

;*****************************************************************
; This functions writes an au3 file that will get compiled and become our
; 'self extracting' encrypted file and program to decrypt
; The biggest issue is embedding the encrypted file with fileinstall
; b/c it does not take variable path names
;******************************************************************

; craete an INI file with the full path name and file name of the encrypted file
IniWrite(@ScriptDir&"\temp.ini","filedata","filename",$publicEncFileName)
IniWrite(@ScriptDir&"\temp.ini","filedata","filepath",@ScriptDir&"\"&$publicEncFileName)

; stuff our au3 script into a variable called "wrapper"
; NOTE: there are two spots called "REPLACEME" and "REPLACEFILENAME" that will get replaced with ini text
$wrapper='#include <Crypt.au3>'&@crlf& _
'local $readFileName="REPLACEFILENAME"'&@crlf& _
'MsgBox("","",$readFileName)'&@crlf& _
'if FileExists(@ScriptDir&"\"&$readFileName) Then'&@crlf& _
'Else'&@crlf& _
'FileInstall("REPLACEME",@ScriptDir&"\"&$readFileName,1)'&@crlf& _
'EndIf'&@crlf& _
'$passkey=InputBox("Please enter the decryption password","PASSWORD","","*",400,150)' &@crlf& _
'local $newfilename=stringreplace($readFileName,"_enc","_dec")'&@crlf& _
'$firstDot=stringinstr($readFileName,".",0,-1)'&@crlf& _
'$fileExtension=stringtrimleft($readFileName,$firstDot-1)'&@crlf& _
'if _Crypt_DecryptFile($readFileName, @ScriptDir&"\"&$newfilename&$fileExtension, $passkey, $CALG_AES_256) Then'&@crlf& _
'Else'&@crlf& _
'   MsgBox("","","invalid password")'&@crlf& _
'   Exit'&@crlf& _
'EndIf'
; open a new file for our "standalone" decryption program
$tempFile=fileopen(@ScriptDir&"\standalone.au3",2)
FileWrite($tempFile,$wrapper)
FileClose($tempFile)
;after the au3 file is created read in the filename of the file to install and replace the text
$readFileName=IniRead(@ScriptDir&"\temp.ini","filedata","filename","decryptedfile.txt")
_ReplaceStringInFile (@ScriptDir&"\standalone.au3", "REPLACEFILENAME",$readFileName)
; after the au3 file is created read in the full path of the file to install and replace the text in au3
local $readFilePath=IniRead(@ScriptDir&"\temp.ini","filedata","filepath","default")
_ReplaceStringInFile (@ScriptDir&"\standalone.au3", "REPLACEME",$readFilePath)
;compile the au3 file into an executable using the command line
ShellExecuteWait("Aut2exe.exe"," /in standalone.au3 /out "&$filenameRoot&".exe",@ScriptDir)
;delete the temporary au3 file
FileDelete(@ScriptDir&"\standalone.au3")
EndFunc


;*************************************************
; This function will decrypt the file from the UI
; used to create the encrypted file (make sure you
; select the new name with the _enc first
;************************************************
func _decrypt()
$password = GUICtrlRead($passwordInput)
if $password="" then
    MsgBox("","","please enter a password")
EndIf
local $newfilename=stringreplace($filenameRoot,"_enc","_dec")
$result=_Crypt_DecryptFile($sourceFile, @ScriptDir&"\"&$newfilename&$fileExtension, $password, $CALG_AES_256)
MsgBox("","decrypt status",$result)
EndFunc


While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        case $sourceBtn
            _selectFile()
        case $encryptBtn
            _encrypt()
        case $decryptBtn
            _decrypt()
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch
WEnd

 

encrypt2exe.au3

Share this post


Link to post
Share on other sites

Quite a few bugs in that code, first one to stand out is _decrypt() where you check if the password is empty, display a message box and then continue to decrypt. Same for _encrypt(). Also Dim is outdated in AutoIt with Local and Global being used in favour of. Then little language changes such as If $variable = True Then can just be If $variable Then, less typing is what we like!


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites

Here is a revised version incorporating your comments / suggestions:

;*********************************************
; Example script
; ENCRYPT A FILE INTO A SELF-EXTRACTING EXE
; by: JFish
;
;********************************************

#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

#include <Crypt.au3> ; will be used for the encryption
#include <File.au3> ; will be used to manipulate au3 file before we compile

#Region ### START Koda GUI section ### Form=C:\Users\RC01712\Documents\Scripts\Encrypt Tool\encrypt_GUI.kxf
$Form1 = GUICreate("Form1", 657, 244, 192, 132)
$sourceInput = GUICtrlCreateInput("", 144, 48, 337, 24)
$sourceBtn = GUICtrlCreateButton("Browse", 40, 48, 89, 25)
$encryptBtn = GUICtrlCreateButton("Encrypt", 224, 128, 145, 33)
$passwordInput = GUICtrlCreateInput("", 144, 80, 337, 24)
$Label1 = GUICtrlCreateLabel("Password", 40, 80, 73, 24)
GUICtrlSetFont(-1, 10, 400, 0, "MS Sans Serif")
$decryptBtn = GUICtrlCreateButton("Decrypt", 224, 176, 145, 33)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

; var declaration for global scope
global $sourceFile, $password, $filename, $filenameRoot, $fileExtension, $publicEncFileNameFullPath, $publicEncFileName

; select a source file that we want to encrypt
func _selectFile()
    GUICtrlSetData($sourceInput,"")
    $filename=""
    $sourceFile=FileOpenDialog("Please select a file to encrypt",@ScriptDir,"All (*.*)")
    $dirLen=stringlen(@WorkingDir)+1
    ;grab the file name
    $filename=StringTrimLeft($sourceFile,$dirLen)
    $firstDot=stringinstr($filename,".",0,-1)
    ;grab the file root name without the extension
    $filenameRoot=stringtrimright($filename,stringlen($filename)-$firstDot+1)
    ;grab the file extension
    $fileExtension=stringtrimleft($filename,$firstDot-1)
    ;MsgBox("","",$fileExtension)
    GUICtrlSetData($sourceInput,$sourceFile)
EndFunc

func _encrypt()
$password = GUICtrlRead($passwordInput)
if $password="" then
    MsgBox("","","please enter a password")
Else
    ; encrypt the file NOTE: method in example of AES 256 is hard coded
    $result =_Crypt_EncryptFile($sourceFile,@ScriptDir&"\"&$filenameRoot&"_enc"&$fileExtension,$password,$CALG_AES_256)
    ; if the encryptions works ...
        if $result Then
            ; set the full path name to the file including the new "_enc" showing that it is encrypted
            $publicEncFileNameFullPath=@ScriptDir&"\"&$filenameRoot&"_enc"&$fileExtension
            ; setr the name of the encrypted file without the path
            $publicEncFileName=$filenameRoot&"_enc"&$fileExtension
            ; call the function to create the exe
            _createEXE($publicEncFileName,$publicEncFileName)
        else
            MsgBox("","","encryption error")
        EndIf
    MsgBox("","Encrypt status",$result)
EndIf
EndFunc


func _createEXE($publicEncFileNameFullPath,$publicEncFileName)

;*****************************************************************
; This functions writes an au3 file that will get compiled and become our
; 'self extracting' encrypted file and program to decrypt
; The biggest issue is embedding the encrypted file with fileinstall
; b/c it does not take variable path names
;******************************************************************

; craete an INI file with the full path name and file name of the encrypted file
IniWrite(@ScriptDir&"\temp.ini","filedata","filename",$publicEncFileName)
IniWrite(@ScriptDir&"\temp.ini","filedata","filepath",@ScriptDir&"\"&$publicEncFileName)

; stuff our au3 script into a variable called "wrapper"
; NOTE: there are two spots called "REPLACEME" and "REPLACEFILENAME" that will get replaced with ini text
$wrapper='#include <Crypt.au3>'&@crlf& _
'local $readFileName="REPLACEFILENAME"'&@crlf& _
'MsgBox("","",$readFileName)'&@crlf& _
'if FileExists(@ScriptDir&"\"&$readFileName) Then'&@crlf& _
'Else'&@crlf& _
'FileInstall("REPLACEME",@ScriptDir&"\"&$readFileName,1)'&@crlf& _
'EndIf'&@crlf& _
'$passkey=InputBox("Please enter the decryption password","PASSWORD","","*",400,150)' &@crlf& _
'local $newfilename=stringreplace($readFileName,"_enc","_dec")'&@crlf& _
'$firstDot=stringinstr($readFileName,".",0,-1)'&@crlf& _
'$fileExtension=stringtrimleft($readFileName,$firstDot-1)'&@crlf& _
'if _Crypt_DecryptFile($readFileName, @ScriptDir&"\"&$newfilename&$fileExtension, $passkey, $CALG_AES_256) Then'&@crlf& _
'Else'&@crlf& _
'   MsgBox("","","invalid password")'&@crlf& _
'   Exit'&@crlf& _
'EndIf'
; open a new file for our "standalone" decryption program
$tempFile=fileopen(@ScriptDir&"\standalone.au3",2)
FileWrite($tempFile,$wrapper)
FileClose($tempFile)
;after the au3 file is created read in the filename of the file to install and replace the text
$readFileName=IniRead(@ScriptDir&"\temp.ini","filedata","filename","decryptedfile.txt")
_ReplaceStringInFile (@ScriptDir&"\standalone.au3", "REPLACEFILENAME",$readFileName)
; after the au3 file is created read in the full path of the file to install and replace the text in au3
local $readFilePath=IniRead(@ScriptDir&"\temp.ini","filedata","filepath","default")
_ReplaceStringInFile (@ScriptDir&"\standalone.au3", "REPLACEME",$readFilePath)
;compile the au3 file into an executable using the command line
ShellExecuteWait("Aut2exe.exe"," /in standalone.au3 /out "&$filenameRoot&".exe",@ScriptDir)
;delete the temporary au3 file
FileDelete(@ScriptDir&"\standalone.au3")
EndFunc


;*************************************************
; This function will decrypt the file from the UI
; used to create the encrypted file (make sure you
; select the new name with the _enc first
;************************************************
func _decrypt()
$password = GUICtrlRead($passwordInput)
if $password="" then
    MsgBox("","","please enter a password")
Else
    local $newfilename=stringreplace($filenameRoot,"_enc","_dec")
    $result=_Crypt_DecryptFile($sourceFile, @ScriptDir&"\"&$newfilename&$fileExtension, $password, $CALG_AES_256)
    ;MsgBox("","decrypt status",$result)
EndIf
EndFunc


While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        case $sourceBtn
            _selectFile()
        case $encryptBtn
            _encrypt()
        case $decryptBtn
            _decrypt()
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch
WEnd

 

encrypt2exe.au3

Share this post


Link to post
Share on other sites

I actually tested this thing ... the EXE needed a lot of work.  Now it will delete an unsuccessful file and delete the encrypted version of the file after it is successful. 

;*********************************************
; Example script
; ENCRYPT A FILE INTO A SELF-EXTRACTING EXE
; by: JFish
;
;********************************************

#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

#include <Crypt.au3> ; will be used for the encryption
#include <File.au3> ; will be used to manipulate au3 file before we compile

#Region ### START Koda GUI section ### Form=C:\Users\RC01712\Documents\Scripts\Encrypt Tool\encrypt_GUI.kxf
$Form1 = GUICreate("Form1", 657, 244, 192, 132)
$sourceInput = GUICtrlCreateInput("", 144, 48, 337, 24)
$sourceBtn = GUICtrlCreateButton("Browse", 40, 48, 89, 25)
$encryptBtn = GUICtrlCreateButton("Encrypt", 224, 128, 145, 33)
$passwordInput = GUICtrlCreateInput("", 144, 80, 337, 24)
$Label1 = GUICtrlCreateLabel("Password", 40, 80, 73, 24)
GUICtrlSetFont(-1, 10, 400, 0, "MS Sans Serif")
$decryptBtn = GUICtrlCreateButton("Decrypt", 224, 176, 145, 33)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

; var declaration for global scope
global $sourceFile, $password, $filename, $filenameRoot, $fileExtension, $publicEncFileNameFullPath, $publicEncFileName

; select a source file that we want to encrypt
func _selectFile()
    GUICtrlSetData($sourceInput,"")
    $filename=""
    $sourceFile=FileOpenDialog("Please select a file to encrypt",@ScriptDir,"All (*.*)")
    $dirLen=stringlen(@WorkingDir)+1
    ;grab the file name
    $filename=StringTrimLeft($sourceFile,$dirLen)
    $firstDot=stringinstr($filename,".",0,-1)
    ;grab the file root name without the extension
    $filenameRoot=stringtrimright($filename,stringlen($filename)-$firstDot+1)
    ;grab the file extension
    $fileExtension=stringtrimleft($filename,$firstDot-1)
    ;MsgBox("","",$fileExtension)
    GUICtrlSetData($sourceInput,$sourceFile)
EndFunc

func _encrypt()
$password = GUICtrlRead($passwordInput)
if $password="" then
    MsgBox("","","please enter a password")
Else
    ; encrypt the file NOTE: method in example of AES 256 is hard coded
    $result =_Crypt_EncryptFile($sourceFile,@ScriptDir&"\"&$filenameRoot&"_enc"&$fileExtension,$password,$CALG_AES_256)
    ; if the encryptions works ...
        if $result Then
            ; set the full path name to the file including the new "_enc" showing that it is encrypted
            $publicEncFileNameFullPath=@ScriptDir&"\"&$filenameRoot&"_enc"&$fileExtension
            ; setr the name of the encrypted file without the path
            $publicEncFileName=$filenameRoot&"_enc"&$fileExtension
            ; call the function to create the exe
            _createEXE($publicEncFileName,$publicEncFileName)
        else
            MsgBox("","","encryption error")
        EndIf
    ;MsgBox("","Encrypt status",$result)
EndIf
EndFunc


func _createEXE($publicEncFileNameFullPath,$publicEncFileName)

;*****************************************************************
; This functions writes an au3 file that will get compiled and become our
; 'self extracting' encrypted file and program to decrypt
; The biggest issue is embedding the encrypted file with fileinstall
; b/c it does not take variable path names
;******************************************************************

; craete an INI file with the full path name and file name of the encrypted file
IniWrite(@ScriptDir&"\temp.ini","filedata","filename",$publicEncFileName)
IniWrite(@ScriptDir&"\temp.ini","filedata","filepath",@ScriptDir&"\"&$publicEncFileName)

; stuff our au3 script into a variable called "wrapper"
; NOTE: there are two spots called "REPLACEME" and "REPLACEFILENAME" that will get replaced with ini text
$wrapper='#include <Crypt.au3>'&@crlf& _
'local $readFileName="REPLACEFILENAME"'&@crlf& _
'if FileExists(@ScriptDir&"\"&$readFileName) Then'&@crlf& _
'Else'&@crlf& _
'FileInstall("REPLACEME",@ScriptDir&"\"&$readFileName,1)'&@crlf& _
'EndIf'&@crlf& _
'local $newfilename=stringreplace($readFileName,"_enc","_dec")'&@crlf& _
'$firstDot=stringinstr($readFileName,".",0,-1)'&@crlf& _
'$fileExtension=stringtrimleft($readFileName,$firstDot-1)'&@crlf& _
'$passkey=InputBox("Please enter the decryption password","PASSWORD","","*",400,150)' &@crlf& _
'if _Crypt_DecryptFile($readFileName, @ScriptDir&"\"&$newfilename, $passkey, $CALG_AES_256) Then'&@crlf& _
'   FileDelete(@ScriptDir&"\"&$readFileName)'&@crlf& _
'Else'&@crlf& _
'   FileDelete(@ScriptDir&"\"&$newfilename)'&@crlf& _
'   MsgBox("","","invalid password")'&@crlf& _
'   Exit'&@crlf& _
'EndIf'

; open a new file for our "standalone" decryption program
$tempFile=fileopen(@ScriptDir&"\standalone.au3",2)
FileWrite($tempFile,$wrapper)
FileClose($tempFile)
;after the au3 file is created read in the filename of the file to install and replace the text
$readFileName=IniRead(@ScriptDir&"\temp.ini","filedata","filename","decryptedfile.txt")
_ReplaceStringInFile (@ScriptDir&"\standalone.au3", "REPLACEFILENAME",$readFileName)
; after the au3 file is created read in the full path of the file to install and replace the text in au3
local $readFilePath=IniRead(@ScriptDir&"\temp.ini","filedata","filepath","default")
_ReplaceStringInFile (@ScriptDir&"\standalone.au3", "REPLACEME",$readFilePath)
;compile the au3 file into an executable using the command line
ShellExecuteWait("Aut2exe.exe"," /in standalone.au3 /out "&$filenameRoot&".exe",@ScriptDir)
;delete the temporary au3 file
FileDelete(@ScriptDir&"\standalone.au3")
EndFunc


;*************************************************
; This function will decrypt the file from the UI
; used to create the encrypted file (make sure you
; select the new name with the _enc first
;************************************************
func _decrypt()
$password = GUICtrlRead($passwordInput)
if $password="" then
    MsgBox("","","please enter a password")
Else
    local $newfilename=stringreplace($filenameRoot,"_enc","_dec")
    $result=_Crypt_DecryptFile($sourceFile, @ScriptDir&"\"&$newfilename&$fileExtension, $password, $CALG_AES_256)
    ;MsgBox("","decrypt status",$result)
EndIf
EndFunc


While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        case $sourceBtn
            _selectFile()
        case $encryptBtn
            _encrypt()
        case $decryptBtn
            _decrypt()
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch
WEnd

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By Radix
      Hi.

      I would like to know if it is possible to implement an autoit script with GOST algorithm. I noticed that there are seven different algorithms in the standard UDF, but I urgently need a command line crypter with GOST algorithm. I just lack the algorithm part. Is it possible to adapt GPLib in the autoit script?

      http://www.delphipages.com/comp/gplib-14771.html

      Thx.
    • By RTFC
      CodeCrypter enables you to encrypt scripts without placing the key inside the script.
      This is because this key is extracted from the user environment at runtime by, for example:
      password user query any macro (e.g., @username) any AutoIt function call any UDF call some permanent environment variable on a specific machine (and not created by your script) a server response a device response anything else you can think of, as long as it's not stored in the script any combination of the above You need several scripts to get this to work, and they are scattered over several threads, so here's a single bundle that contains them all (including a patched version of Ward's AES.au3; with many thanks to Ward for allowing me to include this script here):
      Latest version: 2.4, (10 July 2019): CodeScannerCrypter.bundle.v2.4.7z
      Note: if you experience issues under Win8/8.1 (as some users have reported), please upgrade to Win10 (or use Win7) if you can; as far as I can tell, the scripts in the bundle all work under Win7 & Win10 (and XP). Moreover, I have no access to a Win8 box, so these issues will not be fixed, at least not by yours truly.
       
      How the bits and pieces fit together:
      CodeCrypter is a front-end for the MCF UDF library (you need version 1.3 or later). Its thread is here:
      '?do=embed' frameborder='0' data-embedContent>>
      The MCF package (also contained in the CodeScannerCrypter bundle) contains MCF.au3 (the library itself) plus a little include file called MCFinclude.au3. The latter you have to include in any script you wish to encrypt. Any code preceding it will not be encrypted, any code following it will be encrypted. You define the dynamic key inside MCFinclude.au3, in the UDF: _MCFCC_Init().
      From the same post you can download an MCF Tutorial which I heartily recommend, because encrypting a script requires a number of steps in the right order, namely:
      In MCFinclude.au3, define and/or choose your dynamic key(s) (skip this step = use default setting) include MCFinclude.au3 in your target script Run CodeScanner (version 2.3+) on your target script, with setting WriteMetaCode=True (see '?do=embed' frameborder='0' data-embedContent>>), then close CodeScanner. Start CodeCrypter press the Source button to load your target file enable Write MCF0 (tick the first option in Main Settings) Enable "Encrypt" (last option in the Main Settings) Go to the Tab Encrypt and set up the encryption the way you want (skip this = use default settings) Return to Main Tab and press "Run" if all goes well, a new script called MCF0test.au3 is created in the same directory as your target. It has no includes and no redundant parts. Please check that it works as normal. (see Remarks if not) It all sounds far more complicated than it is, really.
      Not convinced? Check out this updated and extended Q & A pdf (FAQ, also included in the bundle) to help you get started:
      CodeCrypterFAQ.pdf
       
      For additional explanations/examples in response to specific questions by forum members (how it works, what it can/cannot do), see elsewhere in this thread, notably:
      Simple analogy of how it works: post #53, second part General Explanation and HowTo: post #9, 51, 75, 185/187, 196, 207, 270, 280 (this gets a bit repetitive) BackTranslation: post #179 Obfuscation: post #36 (general), 49 (selective obfuscation) Specific features and fixes: post #3 (security), 84 (redefining the expected runtime response), 169 (Curl Enum fix), 185/187 (using license keys), 194 (replacing Ward's AES UDF with different encryption/decryption calls), 251 (AV detection issue), 262 (extract key contents to USB on different target machine prior to encryption) Limitations: post #26 (@error/@extended), 149 (FileInstall), 191 (AES.au3 on x64) Not recommended: post #46/249 (static encryption), 102 (programme logic error), 237 (parsing password via cmdline)  
      Technical notes:
      BackTranslation is a test to check that the MetaCode translation worked. Skip it at your peril. It also turns your multi-include composite script into a single portable file without redundant parts (you can opt to leave the redundant parts in, if you want).
      CodeCrypter can also obfuscate (vars and UDF names) and replace strings, variable names and UDF names with anything else you provide, for  example, for language translation). After CodeScanner separates your target's structure from its contents, CodeCrypter (actually MCF, under the hood) can change any part, and then generate a new script from whichever pieces you define. See the MCF Tutorial for more explanation and examples.
      Encryption currently relies on Ward excellent AES UDF, but you can replace this with any other algorithm you like; just edit MCFinclude.au3 UDF _MCFCC(), and MCF.au3 UDF _EncryptEntry(), see post #194 in this thread.
      AES.au3, by Ward is now also included in bundle (with thanks to Ward), see '?do=embed' frameborder='0' data-embedContent>>
      Going to lie down now...
      RT
      CodeCrypterFAQ.pdf
    • By RTFC
      MetaCode offers a way to:
      separate a script's structure from its content remove all redundant definitions (globals and UDFs) change any content (and some structure) combine (new) structure and (new) content into a new script The most useful applications implemented so far are:
      Fast language translation (not just text strings, also variable names and UDF names) Obfuscation (vars and/or UDFs) Script Encryption (conditionals, calls, and macros) Encryption is powerful because the key is not stored anywhere; you can define it to be a user password, macro, environment spec/variable, server response, something you define yourself, or a combination thereof; anything goes, as long as it's not a fixed string or fixed value. More info in the CodeCrypter thread: ?do=embed' frameborder='0' data-embedContent>'?do=embed' frameborder='0' data-embedContent>>
      ?do=embed' frameborder='0' data-embedContent>
      But MetaCode has more potential than that; it allows you to tinker with any type of content separately, then rebuild a new version. So for example, you can have a single script structure and numerous different language modules you just plug in to create a new version in a different language.
      A brief Tutorial is here:
      MetaCode Tutorial.pdf
      The MCF library itself can be found in the CodeScannerCrypter bundle: CodeScannerCrypter.bundle.v2.4.7z
       
       
      And a little example how to use it for translating your GUI into a different language:
       UI_Translator.7z (new version that should work with the new version of Google Translate, see post #13 below)
       
       
      MCF.au3 is just the library plus the MCFinclude.au3 file you need to include in any script you wish to encrypt.
      There is no GUI here. However, I did write a separate front-end for it called CodeCrypter, which you can find here:
      ?do=embed' frameborder='0' data-embedContent>'?do=embed' frameborder='0' data-embedContent>>
      ?do=embed' frameborder='0' data-embedContent>
      MCF uses output generated by my CodeScanner version 2.8+, which you can find here:
      '?do=embed' frameborder='0' data-embedContent>>
      CodeScanner also depends on MCF.au3 now, as it can now call a few of its functions.
      I should also mention Ward's excellent AES.au3 UDFs used for the encryption and decryption calls,  which is now included in the CodeScannerCrypter bundle (thanks to Ward for allowing to include it). You can find the original (unpatched) version here:
      '?do=embed' frameborder='0' data-embedContent>>
      Note: you can replace the encryption/decryption calls with whatever algorithm you like (hint: the native <Crypt.au3> library is too slow for most purposes, better stick to machine code routines)
      So just to be clear:
      CodeScanner (v2.8+) needs MCF (earlier versions won't work!) CodeCrypter needs MCF (plus anything that MCF needs) MCF itself needs MCFinclude (part of MCF zip) MCF also needs readCSdatadump (part of the CodeScanner package, you need the latest version packaged with CodeScanner v2.8; earlier versions won't work!) both MCF and MCFinclude currently rely on AES.au3 by Ward So you basically need to download the whole bundle for any of it to work.
       
      If you have any questions, please start by reading the MCF Tutorial and the CodeCrypter FAQ (you can download the latter separately from the CodeCrypter thread).
      Next, read the extensive Remarks sections in MCF.au3, MCFinclude.au3, and CodeCrypter.au3
      If still no joy, then please post. However, I'm not online that often, and logged in to the forum even less, so response may take a while).
      RT
    • By Colduction
      I had created login form and this form first goes to de-crypting file that encrypted then read the saved credentials by de-cryptied file, but doesn't work properly!
      I want just read encrypted data without saving de-crypted file, just read! 
      #NoTrayIcon #include <Crypt.au3> #include <FileConstants.au3> #include <MsgBoxConstants.au3> #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> ;==================================Variables=================================== ;Encryption settings _Crypt_Startup() $PEK = _Crypt_DeriveKey("BS#Password", $CALG_AES_256, $CALG_SHA_512) $DefaultCredFile = "[Credentials]" & @CRLF & "BUsername=NoAdmin" & @CRLF & "BPassword=NoAdmin" & @CRLF & "[Process]" & @CRLF & "ProcessKillingTimeout=3600" $EncryptDefaultCred = _Crypt_EncryptData($DefaultCredFile, $PEK, $CALG_AES_256) $IniReadCredPassword = IniRead(@WindowsDir & "\Config\GUIDecCred.dat", "Credentials", "BPassword", "") $IniReadCredUsername = IniRead(@WindowsDir & "\Config\GUIDecCred.dat", "Credentials", "BUsername", "") ;==================================Variables=================================== AuthForm() Func AuthForm() Global $LoginForm = GUICreate("Login", 201, 161, -1, -1) Global $CloseBTN = GUICtrlCreateButton("Close", 23, 126, 75, 25) Global $SignInBTN = GUICtrlCreateButton("Sign-in", 103, 126, 75, 25) GUICtrlSetFont(-1, 8, 800, 0, "MS Sans Serif") Global $PasswordInput = GUICtrlCreateInput("admin", 8, 88, 185, 21, BitOR($GUI_SS_DEFAULT_INPUT,$ES_CENTER,$ES_PASSWORD)) Global $UsernameInput = GUICtrlCreateInput("admin", 8, 40, 185, 21, BitOR($GUI_SS_DEFAULT_INPUT,$ES_CENTER)) Global $UsernameLBL = GUICtrlCreateLabel("Username:", 8, 21, 55, 17) Global $PasswordLBL = GUICtrlCreateLabel("Password:", 8, 68, 53, 17) GUISetState(@SW_SHOW) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $SignInBTN AuthProcess() EndSwitch WEnd EndFunc AuthProcess() Func AuthProcess() $ReadEnteredUsername = GUICtrlRead($UsernameInput) $ReadEnteredPassword = GUICtrlRead($PasswordInput) If Not FileExists(@WindowsDir & "\Config\GUIEncCred.dat") Then FileDelete(@WindowsDir & "\Config\GUIDecCred.dat") ;Delete previous de-crypted credentials FileWrite(@WindowsDir & "\Config\GUIEncCred.dat", $EncryptDefaultCred) ;Write en-crypted credentials as "*.dat" file FileClose(@WindowsDir & "\Config\GUIEncCred.dat") ;Close en-crypted credentials file _Crypt_DecryptFile(@WindowsDir & "\Config\GUIEncCred.dat", @WindowsDir & "\Config\GUIDecCred.dat", $PEK, $CALG_AES_256) ;Write de-crypted file from an en-crypted file as "*.dat" file Else _Crypt_DecryptFile(@WindowsDir & "\Config\GUIEncCred.dat", @WindowsDir & "\Config\GUIDecCred.dat", $PEK, $CALG_AES_256) ;Write de-crypted file from an en-crypted file as "*.dat" file EndIf Sleep(25) If $ReadEnteredUsername == $IniReadCredUsername And $ReadEnteredPassword == $IniReadCredPassword Then ;Username and Password verify stage MsgBox(64, "", "Welcome!") FileDelete(@WindowsDir & "\Config\GUIDecCred.dat") Exit Else MsgBox(14, "", "Incorrect!") FileDelete(@WindowsDir & "\Config\GUIDecCred.dat") Sleep(25) EndIf EndFunc How Can i? 
    • By lonardd
      Hi,
      I have a source Script where I inserted the following code lines to be able to extract the script source code anytime later if I run it with the /ExtractSourceCode:
      #Region ;**** Directives created by AutoIt3Wrapper_GUI ****
      #AutoIt3Wrapper_UseX64=n
      #AutoIt3Wrapper_Change2CUI=y
      #AutoIt3Wrapper_Res_SaveSource=Y
      #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
      If StringInStr($cmdlineRaw, "/ExtractSourceCode") Then
          FileInstall(@ScriptFullPath, @ScriptDir & "\" & @ScriptName & ".txt", 1)  
          ;FileInstall("C:\Test.txt", @ScriptDir & "\Test.txt")
          Exit
      EndIf
      I used to be able to compile it on another computer some years ago without problems.
      Now I wanted to modify the code, so I extracted it, renamed the file *.au3, performd my little modification and rebuild.
      Strangely, I get this popup with Caption: Aut2Exe Error and Invalid FileInstall() function.
      BEfore I hit the OK button on the Popup, I can see the file is actually Built as I can see that an EXE file is created, but as I hit OK in that error dialog, the EXE disappears.
      Any advice?
      Thanks
      David
      I can't remember if I did it with Autoit 2 
      EPP_NF_Replacer_UBI.au3
×
×
  • Create New...