Jump to content

Recommended Posts

Posted (edited)

Hello.

A couple week ago i've started learning API Interface for different websites. In this fact sometimes you have to encode your "photo" or "document.body" to send request.

Functions to encode and decode Base64 was already created by others. Unfortunately i have troubles with running it on Windows R 2008, also speed was terrible.

I try to find alternative way to code data. 

I've read about Microsoft "XMLDOM" and created a one simple function to Encode / Decode data to base64binary, base64url

Thanks for Ghads on Wordpress i coverted a part of his lines from VBscript to AutoIT

;==============================================================================================================================
; Function:         base64($vCode [, $bEncode = True [, $bUrl = False]])
;
; Description:      Decode or Encode $vData using Microsoft.XMLDOM to Base64Binary or Base64Url.
;                   IMPORTANT! Encoded base64url is without @LF after 72 lines. Some websites may require this.
;
; Parameter(s):     $vData      - string or integer | Data to encode or decode.
;                   $bEncode    - boolean           | True - encode, False - decode.
;                   $bUrl       - boolean           | True - output is will decoded or encoded using base64url shema.
;
; Return Value(s):  On Success - Returns output data
;                   On Failure - Returns 1 - Failed to create object.
;
; Author (s):       (Ghads on Wordpress.com), Ascer
;===============================================================================================================================
Func base64($vCode, $bEncode = True, $bUrl = False)

    Local $oDM = ObjCreate("Microsoft.XMLDOM")
    If Not IsObj($oDM) Then Return SetError(1, 0, 1)

    Local $oEL = $oDM.createElement("Tmp")
    $oEL.DataType = "bin.base64"

    If $bEncode then
        $oEL.NodeTypedValue = Binary($vCode)
        If Not $bUrl Then Return $oEL.Text
        Return StringReplace(StringReplace(StringReplace($oEL.Text, "+", "-"),"/", "_"), @LF, "")
    Else
        If $bUrl Then $vCode = StringReplace(StringReplace($vCode, "-", "+"), "_", "/")
        $oEL.Text = $vCode
        Return $oEL.NodeTypedValue
    EndIf

EndFunc ;==>base64

 

 

Edited by Ascer
Posted

Here you are.

Local $vData = "Hello jcpetu this is an example using base64 func.khsfishfiagsfgiy9047019tcDV:{:J{B:CSgAAFCACXC>N<@#$%#$^@@#%@#$^TCCCCCKGAS GZG"

print("Your data for this example is [" & $vData & "]" & @CRLF)

print("1. Method: String -> Base64Binary")
Local $sBase64Binary = base64($vData)
print("Output: " & $sBase64Binary & @CRLF)

print("2. Method: Base64Binary -> String")
print("Output: " & BinaryToString(base64($sBase64Binary, False)) & @CRLF) ; used binary to string because base64 func first convert data to Binary (some web dont do this)

print("3. Method: String -> Base64Url")
Local $sBase64Url = base64($vData, True, True)
print("Output: " & $sBase64Url & @CRLF)

print("4. Method: Base64Url -> String")
print("Output: " & BinaryToString(base64($sBase64Url, False, True)) & @CRLF)

Func print($vData)
    Return ConsoleWrite($vData & @CRLF)
EndFunc   ;==>print()

 

  • 2 months later...
Posted

Thank you Ascer,
that was really useful..


BTW do we need to release the XMLDOM object?
(what is AutoIt's behavior for such objects, if not released bty the developer?)

Posted
  On 4/29/2018 at 7:52 PM, Zohar said:

BTW do we need to release the XMLDOM object?
(what is AutoIt's behavior for such objects, if not released bty the developer?)

Expand  

As far as I know this is released in MS Windows in each version which is currently supported by AutoIt.

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

  Reveal hidden contents

Signature last update: 2023-04-24

Posted

Hmm

Imagine this object being created 20-30 times per minute,
without being explicitly released by the developer..

I think it would be good to release it.

Posted

ah ... you mean cleanup, not distribuate ...
I apologize for my mistake.

AutoIt should destroy each local variable when you exit function, but this is good practices to CleanUp object by assigning value to variable , 
but in this case object is used in Return line so it would be "difficult" .
 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

  Reveal hidden contents

Signature last update: 2023-04-24

  • 1 year later...
Posted
  On 2/18/2018 at 6:04 PM, Ascer said:

Here you are.

Local $vData = "Hello jcpetu this is an example using base64 func.khsfishfiagsfgiy9047019tcDV:{:J{B:CSgAAFCACXC>N<@#$%#$^@@#%@#$^TCCCCCKGAS GZG"

print("Your data for this example is [" & $vData & "]" & @CRLF)

print("1. Method: String -> Base64Binary")
Local $sBase64Binary = base64($vData)
print("Output: " & $sBase64Binary & @CRLF)

print("2. Method: Base64Binary -> String")
print("Output: " & BinaryToString(base64($sBase64Binary, False)) & @CRLF) ; used binary to string because base64 func first convert data to Binary (some web dont do this)

print("3. Method: String -> Base64Url")
Local $sBase64Url = base64($vData, True, True)
print("Output: " & $sBase64Url & @CRLF)

print("4. Method: Base64Url -> String")
print("Output: " & BinaryToString(base64($sBase64Url, False, True)) & @CRLF)

Func print($vData)
    Return ConsoleWrite($vData & @CRLF)
EndFunc   ;==>print()

 

Expand  

Error: The request action with this object failed...

Posted (edited)
  On 12/26/2019 at 9:36 AM, Radix said:

Error: The request action with this object failed...

Expand  

Could you please provide details about your system : OS, AutoIt-Version, etc.

For me, this works :

#cs ----------------------------------------------------------------------------
Source :
https://www.autoitscript.com/forum/topic/192404-base64-autoit-encode-decode-extra-fast/?do=findComment&comment=1380831
-> Uses Microsofts "XMLDOM" and created a one simple function to Encode / Decode data to base64binary, base64url
#ce ----------------------------------------------------------------------------


; -----------------------------------------------------------------------------------------
; Example :
; -----------------------------------------------------------------------------------------
Local $vData = "Hello jcpetu this is an example using base64 func.khsfishfiagsfgiy9047019tcDV:{:J{B:CSgAAFCACXC>N<@#$%#$^@@#%@#$^TCCCCCKGAS GZG"

print("Your data for this example is [" & $vData & "]" & @CRLF)

print("1. Method: String -> Base64Binary")
Local $sBase64Binary = base64($vData)
print("Output: " & $sBase64Binary & @CRLF)

print("2. Method: Base64Binary -> String")
print("Output: " & BinaryToString(base64($sBase64Binary, False)) & @CRLF) ; used binary to string because base64 func first convert data to Binary (some web dont do this)

print("3. Method: String -> Base64Url")
Local $sBase64Url = base64($vData, True, True)
print("Output: " & $sBase64Url & @CRLF)

print("4. Method: Base64Url -> String")
print("Output: " & BinaryToString(base64($sBase64Url, False, True)) & @CRLF)


Func print($vData)
    Return ConsoleWrite($vData & @CRLF)
EndFunc   ;==>print()
; -----------------------------------------------------------------------------------------


;==============================================================================================================================
; Function:         base64($vCode [, $bEncode = True [, $bUrl = False]])
;
; Description:      Decode or Encode $vData using Microsoft.XMLDOM to Base64Binary or Base64Url.
;                   IMPORTANT! Encoded base64url is without @LF after 72 lines. Some websites may require this.
;
; Parameter(s):     $vData      - string or integer | Data to encode or decode.
;                   $bEncode    - boolean           | True - encode, False - decode.
;                   $bUrl       - boolean           | True - output is will decoded or encoded using base64url shema.
;
; Return Value(s):  On Success - Returns output data
;                   On Failure - Returns 1 - Failed to create object.
;
; Author (s):       (Ghads on Wordpress.com), Ascer
;===============================================================================================================================
Func base64($vCode, $bEncode = True, $bUrl = False)

    Local $oDM = ObjCreate("Microsoft.XMLDOM")
    If Not IsObj($oDM) Then Return SetError(1, 0, 1)

    Local $oEL = $oDM.createElement("Tmp")
    $oEL.DataType = "bin.base64"

    If $bEncode then
        $oEL.NodeTypedValue = Binary($vCode)
        If Not $bUrl Then Return $oEL.Text
        Return StringReplace(StringReplace(StringReplace($oEL.Text, "+", "-"),"/", "_"), @LF, "")
    Else
        If $bUrl Then $vCode = StringReplace(StringReplace($vCode, "-", "+"), "_", "/")
        $oEL.Text = $vCode
        Return $oEL.NodeTypedValue
    EndIf

EndFunc ;==>base64

 

Edit  @Radix : Also have a look at this script from @trancexx : _base64encode-_base64decode

  Reveal hidden contents
Edited by Musashi
added second script

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Posted

Addition :
I have written a small test script for people who are interested to compare the versions of @trancexx and @Ascer .

You can 'play around' with it and make your own decision ;).

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <StringConstants.au3>

Opt("MustDeclareVars", 1)

Global $g_sEncoded, $g_sDecoded, $g_sString, $g_iTime

; Bigtext :
Global $g_sString = BinaryToString(InetRead("https://www.autoitscript.com/forum/"), 4)
;~ Global $g_sString = "Hello World, öäü ÖÄÜ ß" ; for simple tests

ConsoleWrite(@CRLF)
ConsoleWrite("+ >> StringLen = " & StringLen($g_sString) & @CRLF)

; ----------- Trancexx : ---------------
ConsoleWrite(@CRLF)
ConsoleWrite("+ >>>>> Trancexx <<<<< :" & @CRLF)

; Encode :
$g_iTime = TimerInit()
$g_sEncoded = _Base64Encode($g_sString)
$g_iTime = TimerDiff($g_iTime)
ConsoleWrite(StringFormat("% 25s: %10.3f ms", "Trancexx Encoding Time", $g_iTime))
ConsoleWrite(@CRLF)

; Decode :
$g_iTime = TimerInit()
$g_sDecoded = _Base64Decode($g_sEncoded)
$g_iTime = TimerDiff($g_iTime)
ConsoleWrite(StringFormat("% 25s: %10.3f ms", "Trancexx Decoding Time", $g_iTime))
ConsoleWrite(@CRLF)

; !!! don't use this for long strings - better write to file :
ConsoleWrite($g_sEncoded & @CRLF)
ConsoleWrite(BinaryToString($g_sDecoded) & @CRLF)


; ----------- Ascer : ---------------
ConsoleWrite(@CRLF)
ConsoleWrite("+ >>>>> Ascer <<<<< :" & @CRLF)

; Encode :
$g_iTime = TimerInit()
$g_sEncoded =  base64($g_sString)
$g_iTime = TimerDiff($g_iTime)
ConsoleWrite(StringFormat("% 25s: %10.3f ms", "Ascer Encoding Time ", $g_iTime))
ConsoleWrite(@CRLF)

; Decode :
$g_iTime = TimerInit()
$g_sDecoded = base64($g_sEncoded, False)
$g_iTime = TimerDiff($g_iTime)
ConsoleWrite(StringFormat("% 25s: %10.3f ms", "Ascer Decoding Time ", $g_iTime))
ConsoleWrite(@CRLF)

; !!! don't use this for long strings - better write to file :
ConsoleWrite($g_sEncoded & @CRLF)
ConsoleWrite(BinaryToString($g_sDecoded) & @CRLF)


; ======================= Functions : =========================

;---------------------------------------------------------------------------------
; Trancexx :
Func _Base64Encode($input)

    $input = Binary($input)

    Local $struct = DllStructCreate("byte[" & BinaryLen($input) & "]")

    DllStructSetData($struct, 1, $input)

    Local $strc = DllStructCreate("int")

    Local $a_Call = DllCall("Crypt32.dll", "int", "CryptBinaryToString", _
            "ptr", DllStructGetPtr($struct), _
            "int", DllStructGetSize($struct), _
            "int", 1, _
            "ptr", 0, _
            "ptr", DllStructGetPtr($strc))

    If @error Or Not $a_Call[0] Then
        Return SetError(1, 0, "") ; error calculating the length of the buffer needed
    EndIf

    Local $a = DllStructCreate("char[" & DllStructGetData($strc, 1) & "]")

    $a_Call = DllCall("Crypt32.dll", "int", "CryptBinaryToString", _
            "ptr", DllStructGetPtr($struct), _
            "int", DllStructGetSize($struct), _
            "int", 1, _
            "ptr", DllStructGetPtr($a), _
            "ptr", DllStructGetPtr($strc))

    If @error Or Not $a_Call[0] Then
        Return SetError(2, 0, ""); error encoding
    EndIf

    Return DllStructGetData($a, 1)

EndFunc   ;==>_Base64Encode


Func _Base64Decode($input_string)

    Local $struct = DllStructCreate("int")

    Local $a_Call = DllCall("Crypt32.dll", "int", "CryptStringToBinary", _
            "str", $input_string, _
            "int", 0, _
            "int", 1, _
            "ptr", 0, _
            "ptr", DllStructGetPtr($struct, 1), _
            "ptr", 0, _
            "ptr", 0)

    If @error Or Not $a_Call[0] Then
        Return SetError(1, 0, "") ; error calculating the length of the buffer needed
    EndIf

    Local $a = DllStructCreate("byte[" & DllStructGetData($struct, 1) & "]")

    $a_Call = DllCall("Crypt32.dll", "int", "CryptStringToBinary", _
            "str", $input_string, _
            "int", 0, _
            "int", 1, _
            "ptr", DllStructGetPtr($a), _
            "ptr", DllStructGetPtr($struct, 1), _
            "ptr", 0, _
            "ptr", 0)

    If @error Or Not $a_Call[0] Then
        Return SetError(2, 0, ""); error decoding
    EndIf

    Return DllStructGetData($a, 1)

EndFunc   ;==>_Base64Decode
;---------------------------------------------------------------------------------


;---------------------------------------------------------------------------------
; Ascer
;==============================================================================================================================
; Function:         base64($vCode [, $bEncode = True [, $bUrl = False]])
;
; Description:      Decode or Encode $vData using Microsoft.XMLDOM to Base64Binary or Base64Url.
;                   IMPORTANT! Encoded base64url is without @LF after 72 lines. Some websites may require this.
;
; Parameter(s):     $vData      - string or integer | Data to encode or decode.
;                   $bEncode    - boolean           | True - encode, False - decode.
;                   $bUrl       - boolean           | True - output is will decoded or encoded using base64url shema.
;
; Return Value(s):  On Success - Returns output data
;                   On Failure - Returns 1 - Failed to create object.
;
; Author (s):       (Ghads on Wordpress.com), Ascer
;===============================================================================================================================
Func base64($vCode, $bEncode = True, $bUrl = False)

    Local $oDM = ObjCreate("Microsoft.XMLDOM")
    If Not IsObj($oDM) Then Return SetError(1, 0, 1)

    Local $oEL = $oDM.createElement("Tmp")
    $oEL.DataType = "bin.base64"

    If $bEncode then
        $oEL.NodeTypedValue = Binary($vCode)
        If Not $bUrl Then Return $oEL.Text
        Return StringReplace(StringReplace(StringReplace($oEL.Text, "+", "-"),"/", "_"), @LF, "")
    Else
        If $bUrl Then $vCode = StringReplace(StringReplace($vCode, "-", "+"), "_", "/")
        $oEL.Text = $vCode
        Return $oEL.NodeTypedValue
    EndIf

EndFunc ;==>base64
;---------------------------------------------------------------------------------

My result :
The version from trancexx is faster. With extremely long strings, the version from Ascer caused an error message during decoding (on my system).

 

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

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
×
×
  • Create New...