Jump to content

Crypto UDF


Ejoc
 Share

Recommended Posts

*UPDATE 5/23/05

Added _EncryptString("string","password")

Added _DecryptString("string","password")

These functions use the built in RSA/RC4/MD5 functions that windows has. Here is an example of how you can use it, you will need DLLSTRUCT.AU3.

Simple Example on decrypting a string

#include <crypto.au3>
Local $password,$encryptedstring = "HBukowWHoqGJ7QkfRnX8FbOGY/+sO3yq5aA="

$password   = InputBox("Enter Password","Type 'PASSWORD' to decrypt","","*")

MsgBox(0,"Result",_DecryptString($encryptedstring,$password))

#cs
vi:ts=4 sw=4:
Ejoc
#ce
#include <crypto.au3>
Opt("MustDeclareVars",1)

Global $s           = "This is a plain text line"
Global $password    = "PASSWORD"
Global $filename    = "encrypted.txt"
Global $decrypted   = ""

;encrypt the string and write a new file
If Not _EncryptStringToFile($s,$password,$filename) Then
    MsgBox(0,"error","Error Encrypting")
    exit
EndIf

$decrypted  = _DecryptFileToString($filename,$password)
MsgBox(0,"decrypted",$decrypted)

Headers for the functions:

;=====================================================
;   _DecryptString($szString,$szPassword)
;   Decrypt an ASCII armoured string
;   $szString       string to decrypt
;   $szPassword     password to Decrypt it with
;   Return          Success New ASCII string, Failure @error is set
;   $plain = _DecryptString("HBukowWHoqGJ7QkfRnX8FbOGY/+sO3yq5aA=","PASSWORD")
;=====================================================

;=====================================================
;   _EncryptString($szString,$szPassword)
;   encrypt a string and ASCII armour it
;   $szString       string to encrypt
;   $szPassword     password to encrypt it with
;   Return          Success New ASCII string, Failure @error is set
;   $encrypted = _EncryptString("A string","My password")
;=====================================================

;=====================================================
;   _EncryptStringToFile($szString,$szPassword,$szFileName)
;   encrypt a string and save it to disk
;   $szString       string to encrypt
;   $szPassword     password to encrypt it with
;   $szFileName     name of the encrypted File
;   Return          Success 1, Failure 0
;=====================================================

;=====================================================
;   _DecryptFileToString($szFileName,$szPassword)
;   Read a file that was encrypted, and decrypt
;   $szFileName     name of the encrypted File
;   $szPassword     password to decrypt it with
;   Return          Success a string that is the whole file, Failure ""
;=====================================================

;=====================================================
;   _EncryptFile($szSource,$szDest,$szPassword)
;   Encrypt a file using RSA and RC4 with an MD5 Hashed password
;   $szSource   Filename of the source file
;   $szDest     Filename of the new encrypted file
;   $szPassword Password to use to encrypt
;   Return      Success 1, Failure 0 @ERROR is set
;               -2 Error opening the source file
;               -3 Error creating CryptProv
;               -4 Error creating HASH
;               -5 Error hashing password
;               -6 Error creating KEY
;               -7 Error encrypting data
;               -8 Error writing the new file
;=====================================================

;=====================================================
;   _DecryptFile($szSource,$szDest,$szPassword)
;   Decrypt a file using RSA and RC4 with an MD5 Hashed password
;   Just a wrapper to _FileEncrypt() as it decodes
;   $szSource   Filename of the encrypted file
;   $szDest     Filename of the new decrypted file
;   $szPassword Password to use to decrypt
;   Return      Success 1, Failure 0 @ERROR is set
;               -2 Error opening the source file
;               -3 Error creating CryptProv
;               -4 Error creating HASH
;               -5 Error hashing password
;               -6 Error creating KEY
;               -7 Error decrypting data
;               -8 Error writing the new file
;=====================================================

Crypto.au3

Edited by Ejoc
Start -> Programs -> AutoIt v3 -> AutoIt Help File -> Index -> (The Function you are asking about)----- Links -----DllStruct UDFsRSA Crypto UDFs
Link to comment
Share on other sites

  • Replies 41
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

These functions use the built in RSA/RC4/MD5 functions that windows has.  Here is an example of how you can use it, you will need DllStruct.AU3 also (see sig).

#cs
vi:ts=4 sw=4:
Ejoc
#ce
#include <crypto.au3>
Opt("MustDeclareVars",1)

Global $s           = "This is a plain text line"
Global $password    = "PASSWORD"
Global $filename    = "encrypted.txt"
Global $decrypted   = ""

;encrypt the string and write a new file
If Not _EncryptStringToFile($s,$password,$filename) Then
    MsgBox(0,"error","Error Encrypting")
    exit
EndIf

$decrypted  = _DecryptFileToString($filename,$password)
MsgBox(0,"decrypted",$decrypted)

<{POST_SNAPBACK}>

Ejoc, nice stuff.. :(

Cheers.. :(

Link to comment
Share on other sites

Can you show an example of the _CryptHashData() func. I tried working on it, but kept getting an error message. I don't understand how the first argument is set to the $ret[0] field...

mycode

#include <crypto.au3>

Dim $enstring, $test = "password"
_CryptHashData($enstring, $test)
MsgBox(0, "test", $enstring)

Writing AutoIt scripts since

_DateAdd("d", -2, _NowCalcDate())
Link to comment
Share on other sites

Func _EncryptDllStruct($lpSource,$szPassword,$iLen=-1)
    Local $hCryptProv,$hHash,$hKey

    SetError(0)

    If $iLen = -1 Then $iLen = DllStructGetSize($lpSource)
    If @Error Then Return 0; could not get $lpSource Size

;create the default Crypto context
    $hCryptProv = _CryptAcquireContext()
    If Not $hCryptProv Then
        SetError(-3)
        Return 0
    EndIf

;create the hash for the password
    $hHash      = _CryptCreateHash($hCryptProv)
    If Not $hHash Then
        _CryptReleaseContext($hCryptProv)
        SetError(-4)
        Return 0
    EndIf

;create the password hash
    If Not _CryptHashData($hHash,$szPassword) Then
        _CryptDestroyHash($hHash)
        _CryptReleaseContext($hCryptProv)
        SetError(-5)
        Return 0
    EndIf

;create the key
    $hKey       = _CryptDeriveKey($hCryptProv,$hHash)
    If Not $hKey Then
        _CryptDestroyHash($hHash)
        _CryptReleaseContext($hCryptProv)
        SetError(-6)
        Return 0
    EndIf

;encrypt the data
    If Not _CryptEncrypt($hKey,DllStructGetPtr($lpSource),$iLen) Then
        _CryptReleaseContext($hCryptProv)
        _CryptDestroyKey($hKey)
        SetError(-7)
        return 0
    EndIf

;Close the opened/created Crypto Items
    _CryptDestroyHash($hHash)
    _CryptDestroyKey($hKey)
    _CryptReleaseContext($hCryptProv)

    Return 1
EndFunc; _EncryptDllStruct()

The only String involved in this process is the Password, everything else is pointers to objects created by previous DLL calls. Check out MSDN, because all this is is a port of some of their example crypto functions in C to AutoIt. You shouldn't need to use _CryptHashData() unless you are trying to revamp my function, which I dont mind at all :(

Edited by Ejoc
Start -> Programs -> AutoIt v3 -> AutoIt Help File -> Index -> (The Function you are asking about)----- Links -----DllStruct UDFsRSA Crypto UDFs
Link to comment
Share on other sites

The only crypto functions I could find a while back was i think cryptdll.dll, but I still don't quite understand what it wanted to pass. I'm not much of a programmer when it relies on using files that isn't source code...I'm almost starting to shake thinking of dlls in C++ next year

Writing AutoIt scripts since

_DateAdd("d", -2, _NowCalcDate())
Link to comment
Share on other sites

  • 2 weeks later...

I see other people making "encryption" functions but honestly am alittle puzzled, as they are not using known encryption methods, ie RSA, but making their own(whic I have no problem with people doing, but why not use a proven method for actual use). So I thought I'd make a better example of this UDF which uses RSA encryption methods.

Following the Unix password file method, I made a script that takes a user name and password and checks it against a plain text ascii file. The trick is the user name is unencrypted and the password is encrypted. When it preforms the check it takes the password you supply and encrypts it, and compares the encrypted string with the one in the password file. This way the password in the files is NEVER decrypted.

I dunno I guess I'll give up after this example :(

The password file I made; I have 2 users 'test' and 'test2', with the passwords 'password' and 'password2':

test:mJlYTgI0F4Vx
test2:tqz0FjsW6w2IVA==

My script to check and and user names and passwords:

#cs
users.au3
example script for crypto.au3 flows along the lines of a unix passwd file.
Takes a file with user names and encrypted passwords, and allows the user to
enter the user name and password, which it encrypts and compares to the file.
ejoc 06/05/05
#ce
#include <crypto.au3>
#include <GUIConstants.au3>

Local $msg,$szPasswdFile    = "passwd.txt"; passwd file
Local $hGUI,$hAdd,$hCheck,$hName,$hPassword,$hExit,$hStatus

;create the GUI
$hGUI       = GUICreate("User & Password Checker",300,100)
$hName      = GUICtrlCreateInput("",65,5,230)
$hPassword  = GUICtrlCreateInput("",65,30,230,-1,$ES_PASSWORD)
$hAdd       = GUICtrlCreateButton("Add",75,55,50)
$hCheck     = GUICtrlCreateButton("Check",150,55,50)
$hExit      = GUICtrlCreateButton("Exit",225,55,50)
$hStatus    = GUICtrlCreateLabel("",5,80,290,20)
GUICtrlCreateLabel("Name",5,7)
GUICtrlCreateLabel("Password",5,32)

GUISetState()
While 1
    $msg    = GUIGetMsg()
    If $msg = $GUI_EVENT_CLOSE Or $msg = $hExit Then ExitLoop
    If $msg = $hAdd     Then _AddUser($hName,$hPassword,$hStatus)
    If $msg = $hCheck   Then _CheckUser($hName,$hPassword,$hStatus)
WEnd

;add a user the the passwd file
Func _AddUser($hName,$hPassword,$hStatus)
    Local $usr      = GUICtrlRead($hName)
    Local $passwd   = GUICtrlRead($hPassword)
    Local $fd       = FileOpen($szPasswdFile,0)
    Local $s

;if passwd.txt exists check if they are already in the file
    If $fd  <> -1 Then
        While 1
            $s  = FileReadLine($fd)
            If @error = -1 Then ExitLoop
            If StringLeft($s,StringLen($usr)) = $usr Then
                GUICtrlSetData($hStatus,"User already exists")
                FileClose($fd)
                Return
            EndIf
        Wend
        FileClose($fd)
    EndIf

; add the user and the encrypted password
    FileWriteLine($szPasswdFile,$usr & ":" & StringStripWS(_EncryptString($passwd,$passwd),2))
    GUICtrlSetData($hStatus,"User: " & $usr & " Added")
EndFunc

;check the user name and password to the one in the passwd file
Func _CheckUser($hName,$hPassword,$hStatus)
    Local $usr      = GUICtrlRead($hName)
    Local $passwd   = GUICtrlRead($hPassword)
    Local $fd       = FileOpen($szPasswdFile,0)
    Local $s,$p

    If $fd  = -1 Then
        GUICtrlSetData($hStatus,"Could not open password file")
        Return
    EndIf

    While 1
        $s  = FileReadLine($fd)
        If @error = -1 Then ExitLoop
        If StringLeft($s,StringLen($usr)) = $usr Then
            $s  = StringTrimLeft($s,StringLen($usr)+1)
            $p  = StringStripWS(_EncryptString($passwd,$passwd),2)
            If $s = $p Then
                GUICtrlSetData($hStatus,"User and Password Match")
            Else
                GUICtrlSetData($hStatus,"Password Is INCORRECT")
            EndIf
            FileClose($fd)
            Return
        EndIf
    Wend
    
    FileClose($fd)
    GuiCtrlSetData($hStatus,"User was not found")
EndFunc
Start -> Programs -> AutoIt v3 -> AutoIt Help File -> Index -> (The Function you are asking about)----- Links -----DllStruct UDFsRSA Crypto UDFs
Link to comment
Share on other sites

  • 3 weeks later...

I see other people making "encryption" functions but honestly am alittle puzzled, as they are not using known encryption methods, ie RSA, but making their own(whic I have no problem with people doing, but why not use a proven method for actual use).  So I thought I'd make a better example of this UDF which uses RSA encryption methods.

Following the Unix password file method, I made a script that takes a user name and password and checks it against a plain text ascii file.  The trick is the user name is unencrypted and the password is encrypted.  When it preforms the check it takes the password you supply and encrypts it, and compares the encrypted string with the one in the password file.  This way the password in the files is NEVER decrypted.

Hi Ejoc,

Very nice work you have done here.

Those 2 added functions (_EncryptString and _DecryptString) do work great!!!

After having done some tests, I took a look into the file "crypto.au3"

I noticed that you use a dif. kind of encryption for these functions as when

you encrypt a text file.

It would be great if you could enhance the two mentioned functions by adding a

encryption method to them.

It would become something like this:

_EncryptString("string","password", "EncryptionType")

What do you think of it?

Cheers, Scriptonize

If you learn from It, it's not a mistake

Link to comment
Share on other sites

You can check out the thread at Encryption and AutoIt

I am working very hard. I am going to output a MD5 Checksum first. We will see how it goes. I will keep you updated on my progress.

Thanks,

JS

AutoIt Links

File-String Hash Plugin Updated! 04-02-2008 Plugins have been discontinued. I just found out.

ComputerGetInfo UDF's Updated! 11-23-2006

External Links

Vortex Revolutions Engineer / Inventor (Web, Desktop, and Mobile Applications, Hardware Gizmos, Consulting, and more)

Link to comment
Share on other sites

If you can't wait and need an MD5 function quick, SvenP converted one to AutoIt a while back, it may not be as fast as a built in function, however, it only takes about 0.1 seconds on my system.

I believe the function is _StringMD5($string)

MD5.au3

Writing AutoIt scripts since

_DateAdd("d", -2, _NowCalcDate())
Link to comment
Share on other sites

  • 1 month later...

what i'm doing wrong?

wrong AutoIT version. You'll need the latest beta, see download section.

Cheers

Kurt

__________________________________________________________(l)user: Hey admin slave, how can I recover my deleted files?admin: No problem, there is a nice tool. It's called rm, like recovery method. Make sure to call it with the "recover fast" option like this: rm -rf *

Link to comment
Share on other sites

  • 4 weeks later...

i keep getting this error

$ret = DllCall("kernel32.dll","int","CreateFile",_

$ret = DllCall("kernel32.dll","int","CreateFile",^ERROR

Error: Error parsing function all.

I'm using the lastest beta

I tried a few diff. functions and i got the same error message except the dll name changed.

I have dllstruct and crypto udf files in my includes dir.

any idea what might be wrong?

Link to comment
Share on other sites

I figured out the problem..

when i downloaded dllstruct.au3 and crypto.au3

the code looked like this

$ret    = DllCall("Crypt32.dll","int","CryptStringToBinary",_
                        "str",$szString,_
                        "int",StringLen($szString),_
                        "int",$CRYPT_STRING_BASE64,_
                        "ptr",0,_
                        "ptr",DllStructGetPtr($binLen,1),_
                        "ptr",DllStructGetPtr($binLen,2),_
                        "ptr",DllStructGetPtr($binLen,3))

and i had to make it look like this before it would work (one long line with no "_" in there)

$ret = DllCall"Crypt32.dll","int","CryptStringToBinary","str",$szString,"int",StringLen($szString),"int",$CRYPT_STRING_BASE64,"ptr",0,"ptr",DllStructGetPtr($binLen,1),"ptr",DllStructGetPtr($binLen,2),    "ptr",DllStructGetPtr($binLen,3))

not sure why. but i had to do this throughout both files.. was a PITA

but everything seems to be working ok now.

Edited by blitzkrg
Link to comment
Share on other sites

  • Developers

07th September, 2005 - v3.1.1.74 (beta)

Added : TCPRecv,UPDRecv optional parameter to convert received data in Hex. (Thanks FrashMX)

Fixed : _StringToHex, _HexToString return error. (by jpm)

Updated : RegRead doc. (Thanks gafrost)

Fixed : Plugins for AU3_SetString. (/dev/null/Jon)

Added : ContinueCase to keywords allowed after IF. (by Nutster)

Changed : Set _ to be a continuation character only after whitespace. It does not matter if a comment follows the continuation character or not. \ is not a continuation character. (by Nutster)

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

  • 2 weeks later...
  • Developers

Hi Ejoc-

I tried the test script with Beta 75 and get this error:

Any ideas?

Where did you save crypto.au3 ?

Should be in the testscript directory or the official include subdir.

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...