Jump to content

AES 256 encryption in autoit <> php


Recommended Posts

Hi,

I'm trying to get the same AES 256 encryption algorithm in php as in AutoIt, as it gives different results.

AFAIK, it's the same for all algorithms.

Here is what I have :

#include <Crypt.au3>

$s = BinaryToString(_Crypt_EncryptData("mystr", "mykey", $CALG_AES_256))
ConsoleWrite($s & @CrLf) ;ret: ]ÞïW§Q(ç)}§bÖ!è„
$iv=mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);

$s=mcrypt_encrypt(MCRYPT_RIJNDAEL_256, 'mykey', 'mystr', MCRYPT_MODE_ECB, $iv);
echo $s; //ret: —¹±x"ÖêÆí~ðr£)²€M_æ˜ë×.NƒëÜ^ï}
I tried different MCRYPT_MODE constants in php without any success and I don't know if this can be changed in AutoIt.

Thanks for any help.

Br, FireFox.

Link to comment
Share on other sites

I found that the PHP crypt algorithm uses an initialization vector whereas the current Crypt UDF only offers a derive key, hence the difference.

I converted a C script in autoit but it does not work, I would like to know where is my mistake since I have no error. Well, if the IV default value is zero then it's OK.

#include <Crypt.au3>
;~ #include <Array.au3>

;~ HCRYPTPROV hProv = 0;
;~ HCRYPTKEY hKey = 0;
;~ DWORD dwMode;
;~ BYTE pbData[16];
;~ DWORD dwCount;
;~ DWORD i;

Global Const $KP_MODE = 4, $KP_IV = 1

; Get handle to user default provider.
;~ if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) {
_Crypt_Startup()
;~ printf("Error %x during CryptAcquireContext!\n", GetLastError());
;~ goto done;
;~ }
If @error Then
    MsgBox(0, "", "Error %x during CryptAcquireContext!")
    Exit 1
EndIf

; Create random block cipher session key.
;~ if(!CryptGenKey(hProv, CALG_RC2, CRYPT_EXPORTABLE, &hKey)) {
$tKey = DllStructCreate("handle")

$aRet = DllCall(__Crypt_DllHandle(), "bool", "CryptGenKey", _
        "handle", __Crypt_Context(), _
        "uint", $CALG_AES_256, _
        "dword", $CRYPT_EXPORTABLE, _
        "handle*", DllStructGetPtr($tKey, 1))
;~ printf("Error %x during CryptGenKey!\n", GetLastError());
;~ goto done;
;~ }
If @error Or Not $aRet[0] Then
    MsgBox(0, "", "Error %x during CryptGenKey!")
EndIf
DllStructSetData($tKey, 1, $aRet[4])

; Read the cipher mode.
;~ dwCount = sizeof(DWORD);

$tDWORD = DllStructCreate("dword")

$tDwCount = DllStructCreate("int")
DllStructSetData($tDwCount, 1, DllStructGetSize($tDWORD))

;~ if(!CryptGetKeyParam(hKey, KP_MODE, &dwMode, &dwCount, 0)) {
$aRet = DllCall(__Crypt_DllHandle(), "bool", "CryptGetKeyParam", _
        "handle", DllStructGetData($tKey, 1), _
        "dword", $KP_MODE, _
        "ptr", DllStructGetPtr($tDWORD), _
        "dword*", DllStructGetPtr($tDwCount, 1), _
        "dword", 0)
;~ printf("Error %x during CryptGetKeyParam!\n", GetLastError());
;~ goto done;
;~ }
If @error Or Not $aRet[0] Then
    MsgBox(0, "", "Error %x during CryptGetKeyParam!")
EndIf

;~ assert(dwCount==sizeof(BYTE));
; Print out cipher mode.
;~ printf("Default cipher mode:%d\n", dwMode);
ConsoleWrite("Default cipher mode:" & DllStructGetData($tDWORD, 1) & @CrLf)
; Read initialization vector.
;~ dwCount = 16;
DllStructSetData($tDwCount, 1, 16)

;~ if(!CryptGetKeyParam(hKey, KP_IV, pbData, &dwCount, 0)) {
$tData = DllStructCreate("byte[16]")

$aRet = DllCall(__Crypt_DllHandle(), "bool", "CryptGetKeyParam", _
        "handle", DllStructGetData($tKey, 1), _
        "dword", $KP_IV, _
        "ptr", DllStructGetPtr($tData), _
        "dword*", DllStructGetPtr($tDwCount, 1), _
        "dword", 0)
;~ printf("Error %x during CryptGetKeyParam!\n", GetLastError());
;~ goto done;
;~ }
If @error Or Not $aRet[0] Then
    MsgBox(0, "", "Error %x during CryptGetKeyParam!")
EndIf

; Print out initialization vector.
;~ printf("Default IV:");
ConsoleWrite("Default IV:")
;~ for(i=0;i<dwCount;i++) printf("%2.2x ",pbData[i]);
;~ printf("\n");
ConsoleWrite(DllStructGetData($tData, 1) & @CrLf)

; Destroy session key.
;~ if(hKey != 0) CryptDestroyKey(hKey);
_Crypt_DestroyKey(DllStructGetData($tKey, 1))

; Release provider handle.
;~ if(hProv != 0) CryptReleaseContext(hProv, 0);

_Crypt_Shutdown()

Note: I don't know why the crypt key is not set by the function CryptGenKey.

Edit: Anyway, even if this works, I don't know how to use the CryptEncrypt with the IV neither to change it on the PHP side...

Br, FireFox.

Edited by FireFox
Link to comment
Share on other sites

I finally found the problem, it was the padding (Cryptographic Message Syntax Standard.): in PHP the padding is set to zero whereas in advapi32 library (used by AutoIt) it's set to PKCS7.

DOES NOT WORK FOR AN INPUT UPPER THAN 16 CHARS.

Here is the AutoIt code :

#include <Crypt.au3>
#include "Base64.au3"

Global Const $KP_MODE = 4
Global Const $CRYPT_MODE_ECB = 2

_Crypt_Startup()

$key = "abcdefghijuklmno"
$str = "hello world!"

$key = _Crypt_ImportKey($CALG_AES_128, $key)

_Crypt_SetKeyParam($key, $KP_MODE, $CRYPT_MODE_ECB)

$s = _Crypt_EncryptData($str, $key, $CALG_USERKEY)

$s = _Base64Encode($s)
ConsoleWrite("Encrypted: " & $s & @CrLf)

_Crypt_DestroyKey($key)

_Crypt_Shutdown()

;Author: ProgAndy, rewritten by FireFox
;return value: key handle
Func _Crypt_ImportKey($iALG_ID, $sKey)
     Local Const $PLAINTEXTKEYBLOB = 0x8 ;The key is a session key.
     Local Const $CUR_BLOB_VERSION = 2

     Local $bKey = Binary($sKey), $iKeyLen = BinaryLen($bKey)

     Local $tagPUBLICKEYBLOB = "struct; BYTE bType; BYTE bVersion; WORD reserved; dword aiKeyAlg; dword keysize; byte key[" & $iKeyLen & "]; endstruct;"

     Local $tBLOB = DllStructCreate($tagPUBLICKEYBLOB)
     DllStructSetData($tBLOB, "bType", $PLAINTEXTKEYBLOB)
     DllStructSetData($tBLOB, "bVersion", $CUR_BLOB_VERSION)
     DllStructSetData($tBLOB, "aiKeyAlg", $iALG_ID)
     DllStructSetData($tBLOB, "keysize", $iKeyLen)
     DllStructSetData($tBLOB, "key", Binary($bKey))

     Local $aRet = DllCall(__Crypt_DllHandle(), "bool", "CryptImportKey", "handle", __Crypt_Context(), "ptr", DllStructGetPtr($tBLOB), "dword", DllStructGetSize($tBLOB), "ptr", 0, "dword", 0, "ptr*", 0)
     If @error Then Return SetError(2, @error)

     Return SetError(Not $aRet[0], 0, $aRet[6])
EndFunc   ;==>_Crypt_ImportKey

;Author: ProgAndy, rewritten by FireFox
;return value: int (bool)
Func _Crypt_SetKeyParam($hKey, $iParam, $vData, $iFlags = 0, $sDataType = Default)
     If Not $sDataType Or $sDataType = Default Then $sDataType = "ptr"

     Local $aRet = DllCall(__Crypt_DllHandle(), "bool", "CryptSetKeyParam", "handle", $hKey, "dword", $iParam, $sDataType, $vData, "dword", $iFlags)
     If @error Then Return SetError(2, @error)

     Return SetError(Not $aRet[0], 0, $aRet[0])
EndFunc   ;==>_Crypt_SetKeyParam

PHP code :

$block=mcrypt_get_block_size('rijndael-128', 'ecb');

$key='abcdefghijuklmno';
$str='hello world!';

//zero to PKCS7 padding
$pad=$block-(strlen($str)%$block);
$str.=str_repeat(chr($pad), $pad);

$s=mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str,  MCRYPT_MODE_ECB);

echo 'Encrypted: '.base64_encode($s);
Edited by FireFox
Link to comment
Share on other sites

  • 3 months later...

well dude you did a nice job!

how can everybody ignore it :o this is what im looking for  :thumbsup: trying it and will report the result soon  :bye:

 

EDIT:

well but unfortunately its limited to 16 chars  :

maybe i'll just encrypt every 16 chars, combine it then send it to php  :guitar:

Edited by awangn6600
Link to comment
Share on other sites

  • 6 months later...

Been working with this and the encryption side works great.

However, to implement everything, the DECRYPT side is needed as well.

I have the php side working, though having issues with the AutoIt decrypt side and need some help....

Here's the full code - I'll describe the bits below 

#include <Crypt.au3>
#include "Base64.au3"
Global $error
Global $extended

Local $str = "hello world!"
ConsoleWrite("string to encrypt/decrypt is " & $str & @crlf& @crlf)

ConsoleWrite("starting ENCRYPTION" & @crlf)
Local $encrypted = _Cryptshun($str)
if @error or @extended Then
    ConsoleWrite("error on encryption is " & @error & @crlf & "extended is " & @extended & @crlf & "decrypted = " & BinaryToString($encrypted) & @crlf&@CRLF)
else
    ConsoleWrite("$encrypted is " & $encrypted & @crlf&@CRLF)
EndIf

ConsoleWrite("starting DECRYPTION (Binary)" & @crlf)
Local $decrypted = _DeCryptshun($encrypted)
if @error or @extended Then
    ConsoleWrite("error on decryption is " & @error & @crlf & "extended is " & @extended & @crlf & "decrypted = " & BinaryToString($decrypted) & @crlf&@CRLF)
else
    ConsoleWrite("decrypted raw = " & BinaryToString($decrypted) & @crlf&@CRLF)
EndIf
; Things work to here - at least encrypt/decrypt
; We now know that to get the decrypt to work, we need BINARY data
; However, in order to match to the PHP, we need _Base64Encode

; try it with encoding (required to match to the PHP)
ConsoleWrite("starting DECRYPTION with ENCODING , DECODING to binary" & @crlf)
Local $encoded = _Base64Encode($encrypted)
ConsoleWrite("base64encoded is " & $encoded & @crlf)
; at this point I can send to the php and get the correct decrypt, match a code, etc. (php function)
; then return encrypted data (base64encoded) - all that works
; emulating that in this program to simply get DECRYPT to work on this encrypted data

Local $decoded = _Base64Decode($encoded)
ConsoleWrite("base64decoded is " & $decoded & @crlf)
; this is where things fall apart - WHY IS THE DECODE NOT THE SAME AS THE ORIGINAL DATA?
; my thought is that _Base64Decode is broken, but see below - it works fine
; when the data from the ENCODED is simply copied, but it does NOT work when
; run through directly

; this code SHOULD work - once the decode is correct (I think...)
Local $decoded2bin = StringToBinary($decoded)
ConsoleWrite("base64decoded2bin is " & $decoded2bin & @crlf)
$decrypted = _DeCryptshun($decoded2bin)
if @error or @extended Then
    ConsoleWrite("error on decryption is " & @error & @crlf & "extended is " & @extended & @crlf & "decrypted = " & BinaryToString($decrypted) & @crlf& @crlf)
else
    ConsoleWrite("decrypted raw = " & BinaryToString($decrypted) & @crlf& @crlf)
EndIf


ConsoleWrite("TESTING _BASE64ENCODE/DECODE"&@crlf)
$str = "dSbB0RQtD//8xY0fvpso8Q=="
ConsoleWrite("string is " & $str & @crlf)
ConsoleWrite("base64encoded = " & _Base64Encode($str) & @crlf)
ConsoleWrite("base64decoded = " & _Base64Decode(_Base64Encode($str)) & @crlf)



Func _Cryptshun($str)
    ; function to match up with php side encryption/decryption
    ; from http://www.autoitscript.com/forum/topic/150967-aes-256-encryption-in-autoit-php/
Dim Const $KP_MODE = 4
Dim Const $CRYPT_MODE_ECB = 2
_Crypt_Startup()
$key = "abcdefghijuklmno"
$key = _Crypt_ImportKey($CALG_AES_128, $key)

_Crypt_SetKeyParam($key, $KP_MODE, $CRYPT_MODE_ECB)

$s = _Crypt_EncryptData($str, $key, $CALG_USERKEY)
if @error or @extended then
    $error = @error
    $extended = @extended
EndIf
_Crypt_DestroyKey($key)
_Crypt_Shutdown()
;$s = _Base64Encode($s)
Return SetError($error,$extended,$s)
EndFunc

Func _DeCryptshun($str)
Dim Const $KP_MODE = 4
Dim Const $CRYPT_MODE_ECB = 2
_Crypt_Startup()
$key = "abcdefghijuklmno"
$key = _Crypt_ImportKey($CALG_AES_128, $key)
_Crypt_SetKeyParam($key, $KP_MODE, $CRYPT_MODE_ECB)
;$str = _Base64Decode($str)
;ConsoleWrite("base64 decoded string - " & $str & @crlf)
;$str = StringToBinary($str)
;ConsoleWrite("stringtobinary = " & $str & @crlf)
$s = _Crypt_DecryptData($str, $key, $CALG_USERKEY)
if @error or @extended then
    $error = @error
    $extended = @extended
EndIf
_Crypt_DestroyKey($key)
_Crypt_Shutdown()
Return SetError($error,$extended,$s)
EndFunc


;Author: ProgAndy, rewritten by FireFox
;return value: key handle
Func _Crypt_ImportKey($iALG_ID, $sKey)
     Local Const $PLAINTEXTKEYBLOB = 0x8 ;The key is a session key.
     Local Const $CUR_BLOB_VERSION = 2

     Local $bKey = Binary($sKey), $iKeyLen = BinaryLen($bKey)

     Local $tagPUBLICKEYBLOB = "struct; BYTE bType; BYTE bVersion; WORD reserved; dword aiKeyAlg; dword keysize; byte key[" & $iKeyLen & "]; endstruct;"

     Local $tBLOB = DllStructCreate($tagPUBLICKEYBLOB)
     DllStructSetData($tBLOB, "bType", $PLAINTEXTKEYBLOB)
     DllStructSetData($tBLOB, "bVersion", $CUR_BLOB_VERSION)
     DllStructSetData($tBLOB, "aiKeyAlg", $iALG_ID)
     DllStructSetData($tBLOB, "keysize", $iKeyLen)
     DllStructSetData($tBLOB, "key", Binary($bKey))

     Local $aRet = DllCall(__Crypt_DllHandle(), "bool", "CryptImportKey", "handle", __Crypt_Context(), "ptr", DllStructGetPtr($tBLOB), "dword", DllStructGetSize($tBLOB), "ptr", 0, "dword", 0, "ptr*", 0)
     If @error Then Return SetError(2, @error)

     Return SetError(Not $aRet[0], 0, $aRet[6])
EndFunc   ;==>_Crypt_ImportKey

;Author: ProgAndy, rewritten by FireFox
;return value: int (bool)
Func _Crypt_SetKeyParam($hKey, $iParam, $vData, $iFlags = 0, $sDataType = Default)
     If Not $sDataType Or $sDataType = Default Then $sDataType = "ptr"

     Local $aRet = DllCall(__Crypt_DllHandle(), "bool", "CryptSetKeyParam", "handle", $hKey, "dword", $iParam, $sDataType, $vData, "dword", $iFlags)
     If @error Then Return SetError(2, @error)

     Return SetError(Not $aRet[0], 0, $aRet[0])
 EndFunc   ;==>_Crypt_SetKeyParam

Now, to break it down.....

 

I found that, to decrypt the data we just encrypted, we need to have the BINARY data to send to  _Crypt_DecryptData 

up to line 24, that works

However, to go to the PHP side, we need base64encoded data

Taking the encrypted data into _Base64Encode, we come up with "dSbB0RQtD//8xY0fvpso8Q==" - that works when sent to the php decode.

However, it does NOT work when I send it to _Base64Decode - I don't get the same binary data back

_Base64Decode(_Base64Encode($EncryptedData)) = $EncryptedData

should be the equation, shouldn't it???

Testing the _Base64Encode and then _Base64Decode on that string works (line 54-58, where the string was copied from the console screen into the code), though it is not working when sent directly.

I am sure this is some sort of declaration on strings that I'm missing, though I have tried all the StringX() functions and not come up with anything (coming from the php world I'm not used to these declarations yet....)

What it boils down to is - How do I get the same data to come out?

(hopefully I'm making sense - been on this for two days and just really stuck!)

Link to comment
Share on other sites

I've little time to test right now but could that problem be somehow related to >this issue?

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

partial step complete!  

Using the B64DEcode from 

and B64Encode from further down the post returns the SAME data.

Though the code is still not fully working, it gets me past that issue and I can continue  - THANKS.  

Edited by TechCoder
Link to comment
Share on other sites

Once you have good data to work with, it doesn't take long.........  ;)

Here's a fully functioning AutoIt to php encryption/decryption set for you to get started with!  (minimal credits to me - I only put it together - everyone else worked out the hard parts! ;)

AUTOIT CODE (change line 16 from http://example.com/your.php to your php location)

#include <Crypt.au3>
#include <IE.au3>
Global $error
Global $extended

Local $str = "hello world!"
ConsoleWrite("string to encrypt/decrypt is " & $str & @crlf& @crlf)
ConsoleWrite("starting ENCRYPTION" & @crlf)
Local $encrypted = _Cryptshun($str)
if @error or @extended Then
    ConsoleWrite("error on encryption is " & @error & @crlf & "extended is " & @extended & @crlf & "decrypted = " & BinaryToString($encrypted) & @crlf&@CRLF)
else
    ConsoleWrite("$encrypted is " & $encrypted & @crlf&@CRLF)
EndIf

$oIE = _IECreate("http://example.com/your.php?data="&$encrypted,0,0,1)
Local $sText = _IEBodyReadText($oIE)
_IEQuit($oIE)

$decrypted = _DeCryptshun($sText)
if @error or @extended Then
    ConsoleWrite("error on decryption is " & @error & @crlf & "extended is " & @extended & @crlf & "decrypted = " & BinaryToString($decrypted) & @crlf& @crlf)
else
    ConsoleWrite("decrypted raw = " & BinaryToString($decrypted) & @crlf& @crlf)
EndIf


Func _Cryptshun($str)
    ; function to match up with php side encryption/decryption
    ; from http://www.autoitscript.com/forum/topic/150967-aes-256-encryption-in-autoit-php/
Dim Const $KP_MODE = 4
Dim Const $CRYPT_MODE_ECB = 2
_Crypt_Startup()
$key = "abcdefghijuklmno"
$key = _Crypt_ImportKey($CALG_AES_128, $key)

_Crypt_SetKeyParam($key, $KP_MODE, $CRYPT_MODE_ECB)

$s = _Crypt_EncryptData($str, $key, $CALG_USERKEY)
if @error or @extended then
    $error = @error
    $extended = @extended
EndIf
_Crypt_DestroyKey($key)
_Crypt_Shutdown()
$s = _B64Encode($s)
Return SetError($error,$extended,$s)
EndFunc

Func _DeCryptshun($str)
Dim Const $KP_MODE = 4
Dim Const $CRYPT_MODE_ECB = 2
_Crypt_Startup()
$key = "abcdefghijuklmno"
$key = _Crypt_ImportKey($CALG_AES_128, $key)
_Crypt_SetKeyParam($key, $KP_MODE, $CRYPT_MODE_ECB)
$str = _B64Decode($str)
$s = _Crypt_DecryptData($str, $key, $CALG_USERKEY)
if @error or @extended then
    $error = @error
    $extended = @extended
EndIf
_Crypt_DestroyKey($key)
_Crypt_Shutdown()
Return SetError($error,$extended,$s)
EndFunc


;Author: ProgAndy, rewritten by FireFox
;return value: key handle
Func _Crypt_ImportKey($iALG_ID, $sKey)
     Local Const $PLAINTEXTKEYBLOB = 0x8 ;The key is a session key.
     Local Const $CUR_BLOB_VERSION = 2

     Local $bKey = Binary($sKey), $iKeyLen = BinaryLen($bKey)

     Local $tagPUBLICKEYBLOB = "struct; BYTE bType; BYTE bVersion; WORD reserved; dword aiKeyAlg; dword keysize; byte key[" & $iKeyLen & "]; endstruct;"

     Local $tBLOB = DllStructCreate($tagPUBLICKEYBLOB)
     DllStructSetData($tBLOB, "bType", $PLAINTEXTKEYBLOB)
     DllStructSetData($tBLOB, "bVersion", $CUR_BLOB_VERSION)
     DllStructSetData($tBLOB, "aiKeyAlg", $iALG_ID)
     DllStructSetData($tBLOB, "keysize", $iKeyLen)
     DllStructSetData($tBLOB, "key", Binary($bKey))

     Local $aRet = DllCall(__Crypt_DllHandle(), "bool", "CryptImportKey", "handle", __Crypt_Context(), "ptr", DllStructGetPtr($tBLOB), "dword", DllStructGetSize($tBLOB), "ptr", 0, "dword", 0, "ptr*", 0)
     If @error Then Return SetError(2, @error)

     Return SetError(Not $aRet[0], 0, $aRet[6])
EndFunc   ;==>_Crypt_ImportKey

;Author: ProgAndy, rewritten by FireFox
;return value: int (bool)
Func _Crypt_SetKeyParam($hKey, $iParam, $vData, $iFlags = 0, $sDataType = Default)
     If Not $sDataType Or $sDataType = Default Then $sDataType = "ptr"

     Local $aRet = DllCall(__Crypt_DllHandle(), "bool", "CryptSetKeyParam", "handle", $hKey, "dword", $iParam, $sDataType, $vData, "dword", $iFlags)
     If @error Then Return SetError(2, @error)

     Return SetError(Not $aRet[0], 0, $aRet[0])
 EndFunc   ;==>_Crypt_SetKeyParam

 Func _B64Encode($sSource)

    ;####### (BinaryStrLen = 272) ########################################################################################################################
    Local Static $Opcode = '0xC80000008B451499B903000000F7F189C18B5D108B75088B7D0C83FA007401418B060FC8C1E806C0E802D7884703C1E806C0E802D7884702C1E806C0E802D7884701C1E806C0E802D7880783C60383C704E2CD83FA0074288B46FD0FC883FA027411C1E8142430D78847FD66C747FE3D3DEB0DC1E80E243CD78847FEC647FF3DC60700C9C21000'
    Local Static $aMemBuff = DllCall("kernel32.dll", "ptr", "VirtualAlloc", "ptr", 0, "ulong_ptr", BinaryLen($Opcode), "dword", 4096, "dword", 64)
    Local Static $tMem = DllStructCreate('byte[' & BinaryLen($Opcode) & ']', $aMemBuff[0])
    Local Static $set = DllStructSetData($tMem, 1, $Opcode)
    ;####################################################################################################################################################################################

    $sSource = Binary($sSource)
    Local $iLen = BinaryLen($sSource)

    $tSource = DllStructCreate('byte[' & $iLen & ']')
    DllStructSetData($tSource, 1, $sSource)

    Local $tOutput = DllStructCreate('char[' & Ceiling($iLen * (4 / 3) + 3) & ']')
    DllCall("kernel32.dll", "bool", "VirtualProtect", "struct*", $tOutput, "dword_ptr", DllStructGetSize($tOutput), "dword", 0x00000004, "dword*", 0)

    Local $sTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    DllCallAddress('none', DllStructGetPtr($tMem), 'struct*', $tSource, 'struct*', $tOutput, 'str', $sTable, 'uint', $iLen)

    Return DllStructGetData($tOutput, 1)

EndFunc   ;==>_B64Encode

#cs Source
Func _B64Encode($sSource)

    _FasmFunc('str, $sSource, str, $sDest, str, $sTable, uint, $iLen')

    _FasmAdd('mov eax, $iLen') ;    div $iLen / 3 to calculate number of loops
    _FasmAdd('cdq')
    _FasmAdd('mov ecx, 3')
    _FasmAdd('div ecx')
    _FasmAdd('mov ecx, eax') ;      Set loops

    _Fasmadd('mov ebx, $sTable') ;  move table to ebx. Used in xlatb instruction
    _Fasmadd('mov esi, $sSource') ; set esi = source string
    _Fasmadd('mov edi, $sDest') ;   set edi = output string

    _FasmJumpIf('edx = 0, EncodeNext') ; need one extra loop if mod <> 0
    _FasmAdd('inc ecx')

    _FasmAdd('EncodeNext:')
    _Fasmadd('mov eax, [esi]') ;    move 4 bytes from source string to dex
    _FasmAdd('bswap eax') ;         reverse bytes. ex :(Man) 00000000 01101110 01100001 01001101 -> 01001101 01100001 01101110 00000000

    _FasmAdd('shr eax, 6')
    _FasmAdd('shr al, 2')
    _FasmAdd('xlatb')
    _FasmAdd('mov [edi+3], al')

    _FasmAdd('shr eax, 6')
    _FasmAdd('shr al, 2')
    _FasmAdd('xlatb')
    _FasmAdd('mov [edi+2], al')

    _FasmAdd('shr eax, 6')
    _FasmAdd('shr al, 2')
    _FasmAdd('xlatb')
    _FasmAdd('mov [edi+1], al')

    _FasmAdd('shr eax, 6')
    _FasmAdd('shr al, 2')
    _FasmAdd('xlatb')
    _FasmAdd('mov [edi], al')

    _Fasmadd('add esi, 3') ;        increase source by 3 bytes
    _fasmadd('add edi, 4') ;        increase destination by 4 bytes
    _Fasmadd('loop EncodeNext')

    _FasmJumpIf('edx = 0, Finished')

    _Fasmadd('mov eax, [esi-3]') ;
    _FasmAdd('bswap eax')

    _FasmJumpIf('edx = 2, TWO')

    ; If there was only one significant input byte, only the first two base64 digits are picked (12 bits)
    _FasmAdd("ONE:") ;  the four least significant bits of the final 6-bit block are set to zero
    _FasmAdd('shr eax, 20')
    _FasmAdd("and al, 48") ;00110000
    _FasmAdd('xlatb')
    _FasmAdd('mov [edi-3], al')
    _FasmAdd("mov [edi-2], word 15677"); '=='
    _FasmAdd("jmp Finished")

    ; if there were two significant input bytes, the first three base64 digits are picked (18 bits).
    _FasmAdd("TWO:") ;  the two least significant bits of the final 6-bit block are set to zero
    _FasmAdd("shr eax, 14")
    _FasmAdd("and al, 60") ; 60 : 00111100
    _FasmAdd('xlatb')
    _FasmAdd('mov [edi-2], al')
    _FasmAdd('mov [edi-1], byte 61') ; '='

    _FasmAdd('Finished:')
    _Fasmadd('  mov [edi], byte 0') ; terminate string with null
    _FasmEndFunc()

    Return _FasmCompileMC('_B64Encode')

    $sSource = Binary($sSource)
    Local $iLen = BinaryLen($sSource)

    $tSource = DllStructCreate('byte[' & $iLen & ']')
    DllStructSetData($tSource, 1, $sSource)

    Local $tOutput = DllStructCreate('char[' & Ceiling($iLen * (4 / 3) + 3) & ']')
    DllCall("kernel32.dll", "bool", "VirtualProtect", "struct*", $tOutput, "dword_ptr", DllStructGetSize($tOutput), "dword", 0x00000004, "dword*", 0)

    Local $sTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    ConsoleWrite(StringInStr($sTable, '4') & @LF)

    _FasmQuickCall('none', 0, 'struct*', $tSource, 'struct*', $tOutput, 'str', $sTable, 'uint', $iLen)

    Return DllStructGetData($tOutput, 1)

EndFunc   ;==>_B64Encode
#ce

Func _B64Decode($sSource)

    Local Static $Opcode, $tMem, $tRevIndex, $fStartup = True

    If $fStartup Then
        If @AutoItX64 Then
            $Opcode = '0xC800000053574D89C74C89C74889D64889CB4C89C89948C7C10400000048F7F148C7C10300000048F7E14989C242807C0EFF3D750E49FFCA42807C0EFE3D750349FFCA4C89C89948C7C10800000048F7F14889C148FFC1488B064989CD48C7C108000000D7C0C0024188C349C1E30648C1E808E2EF49C1E308490FCB4C891F4883C7064883C6084C89E9E2CB4C89D05F5BC9C3'
        Else
            $Opcode = '0xC8080000FF75108B7D108B5D088B750C8B4D148B06D7C0C00288C2C1E808C1E206D7C0C00288C2C1E808C1E206D7C0C00288C2C1E808C1E206D7C0C00288C2C1E808C1E2060FCA891783C70383C604E2C2807EFF3D75084F807EFE3D75014FC6070089F85B29D8C9C21000'
        EndIf

        Local $aMemBuff = DllCall("kernel32.dll", "ptr", "VirtualAlloc", "ptr", 0, "ulong_ptr", BinaryLen($Opcode), "dword", 4096, "dword", 64)
        $tMem = DllStructCreate('byte[' & BinaryLen($Opcode) & ']', $aMemBuff[0])
        DllStructSetData($tMem, 1, $Opcode)

        Local $aRevIndex[128]
        Local $aTable = StringToASCIIArray('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')
        For $i = 0 To UBound($aTable) - 1
            $aRevIndex[$aTable[$i]] = $i
        Next
        $tRevIndex = DllStructCreate('byte[' & 128 & ']')
        DllStructSetData($tRevIndex, 1, StringToBinary(StringFromASCIIArray($aRevIndex)))

        $fStartup = False
    EndIf

    Local $iLen = StringLen($sSource)
    Local $tOutput = DllStructCreate('byte[' & $iLen + 8 & ']')
    DllCall("kernel32.dll", "bool", "VirtualProtect", "struct*", $tOutput, "dword_ptr", DllStructGetSize($tOutput), "dword", 0x00000004, "dword*", 0)

    Local $tSource = DllStructCreate('char[' & $iLen + 8 & ']')
    DllStructSetData($tSource, 1, $sSource)

    Local $aRet = DllCallAddress('uint', DllStructGetPtr($tMem), 'struct*', $tRevIndex, 'struct*', $tSource, 'struct*', $tOutput, 'uint', (@AutoItX64 ? $iLen : $iLen / 4))

    Return BinaryMid(DllStructGetData($tOutput, 1), 1, $aRet[0])

EndFunc   ;==>_B64Decode

and the php (to put in http://example.com/your.php)

 

<?php

$decrypt = encrypt_decrypt("decrypt",$_GET['data']);
if($decrypt=="hello world!") // <<<-- put your required 'must match' data here
{
$return = "hello human!"; // put your 'what to return' here
echo "<html><head></head><body>" . encrypt_decrypt("encrypt",$return) . "</body></html>";
}
function encrypt_decrypt($action, $string) {
$output = false;
$key = 'abcdefghijuklmno'; // <<<<====== put your secret key here
if( $action == 'encrypt' ) {
$block=mcrypt_get_block_size('rijndael-128', 'ecb');
$pad=$block-(strlen($string)%$block);
$string.=str_repeat(chr($pad), $pad);
$output = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_ECB, $iv);
$output = base64_encode($output);
}
else if( $action == 'decrypt' ){
$output = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($string), MCRYPT_MODE_ECB, $iv);
$output = rtrim($output, "");
$output = preg_replace('/p{Cc}+/u', '', $output);
}
return $output;
}
?>
Link to comment
Share on other sites

Maybe post to the Examples?

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

Link to comment
Share on other sites

  • 2 weeks later...
  • 4 years later...
  • 2 years later...

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...