4

I use Ward's AutoIt Machine Code Algorithm Collection to get base64 encoding of a string in AutoIt:

#Include "Base64.au3"

Dim $Encode = _Base64Encode("ps")
MsgBox(0, 'Base64 Encode Data', $Encode)

The result:

cHM=

PowerShell code to get the base64 encoding of the same string "ps":

$commands = 'ps'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($commands)
$encodedString = [Convert]::ToBase64String($bytes)
$encodedString

What I got is:

cABzAA==

The result from PowerShell is what I want. How to get the same result using AutoIt? I guess this is a character encoding issue.

user4157124
  • 2,809
  • 13
  • 27
  • 42
Just a learner
  • 26,690
  • 50
  • 155
  • 234

3 Answers3

6

When I ran this script:

#Include "Base64.au3"

$Decode = _Base64Decode("cABzAA==")
ConsoleWrite($Decode & @CRLF)

I get the result: 0x70007300. Basically, this means there is a '70' character (p), a '00' character (nul), a '73' character (s), '00' character. You can easily recreate this behavior in AutoIt with a function like this:

#Include "Base64.au3"

Dim $Encode = _Base64WEncode("ps")
ConsoleWrite($Encode & @CRLF)

Func _Base64WEncode($string)
    Local $result = ""
    Local $arr = StringSplit($string, "")
    For $i = 1 To UBound($arr) - 1
        $result &= $arr[$i] & Chr(0)
    Next
    $result = _Base64Encode($result)
    Return $result
EndFunc

The result is: cABzAA==

Somewhat hack-ish, but I'd say it is preferred over full Unicode encoding if that's not what you will ever need.

Jos van Egmond
  • 2,370
  • 15
  • 19
  • 2
    TL;DR version: PowerShell is UCS16LE (UTF16) by virtue of being .NET, so it is encoding as double byte by default. – JasonMArcher Aug 15 '11 at 17:48
2
#Include "Base64.au3"    
#include <MsgBoxConstants.au3>
#include <StringConstants.au3>

Dim $Encode = _Base64Encode(StringToBinary("ps", $SB_UTF16LE))
MsgBox(0, 'Base64 Encode Data', $Encode)

This will give what you want :

cABzAA==
user4157124
  • 2,809
  • 13
  • 27
  • 42
Khristophe
  • 31
  • 5
1

Use ASCII encoding instead of Unicode:

$bytes = [System.Text.Encoding]::ASCII.GetBytes($commands)
MrKWatkins
  • 2,621
  • 1
  • 21
  • 34
  • 1
    Hi MrKWatkins, to me, the result from PowerShell is correct. I need this result from AutoIt. So I can't change the PowerShell code. – Just a learner Aug 15 '11 at 12:29
  • 1
    Ah, sorry, misread. Don't know about AutoIt, however does it have a method for base 64 encoding bytes instead of a string? In which case you could manually convert the string to bytes using Unicode encoding yourself and pass that in. – MrKWatkins Aug 15 '11 at 12:39