Base64 encoder/decoder for Binary data

Post your working scripts, libraries and tools
User avatar
SKAN
Posts: 363
Joined: 29 Sep 2013, 16:58

Base64 encoder/decoder for Binary data

17 Aug 2017, 14:22

A quick rewrite of my old code (posted in archived forum):
https://autohotkey.com/board/topic/8570 ... r-decoder/

Base64Enc() with example

Code: Select all

#NoEnv
#Warn
#SingleInstance, Force
SetWorkingDir %A_ScriptDir% 

File := "ahkicon.png"
If ! FileExist( File )
URLDownloadToFile, http://i.imgur.com/dS56Ewu.png, %File%

FileGetSize, nBytes, %File%
FileRead, Bin, *c %File%
B64Data := Base64Enc( Bin, nBytes, 100, 2 )
MsgBox % Clipboard := B64Data 

Return ;     // end of auto-execcute section //


Base64Enc( ByRef Bin, nBytes, LineLength := 64, LeadingSpaces := 0 ) { ; By SKAN / 18-Aug-2017
Local Rqd := 0, B64, B := "", N := 0 - LineLength + 1  ; CRYPT_STRING_BASE64 := 0x1
  DllCall( "Crypt32.dll\CryptBinaryToString", "Ptr",&Bin ,"UInt",nBytes, "UInt",0x1, "Ptr",0,   "UIntP",Rqd )
  VarSetCapacity( B64, Rqd * ( A_Isunicode ? 2 : 1 ), 0 )
  DllCall( "Crypt32.dll\CryptBinaryToString", "Ptr",&Bin, "UInt",nBytes, "UInt",0x1, "Str",B64, "UIntP",Rqd )
  If ( LineLength = 64 and ! LeadingSpaces )
    Return B64
  B64 := StrReplace( B64, "`r`n" )        
  Loop % Ceil( StrLen(B64) / LineLength )
    B .= Format("{1:" LeadingSpaces "s}","" ) . SubStr( B64, N += LineLength, LineLength ) . "`n" 
Return RTrim( B,"`n" )    
}

Base64Dec() with example

Code: Select all

#NoEnv
#Warn
#SingleInstance, Force
SetWorkingDir %A_ScriptDir% 


Base64ImageData := "
( LTrim Join
  iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAMAAABrrFhUAAAAz1BMVEX///8AAAD7/fwjdCv///+bwJ8SaBv///////9KjFBon26U
  u5j///////////////////////9Oj1VfmmX///////////////8NZRb4+PgJQw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IdxzaJjsAAAAASUVORK5CYII=
)"

nBytes := Base64Dec( Base64ImageData, Bin )

File := FileOpen("ahkiconnew.png", "w")
File.RawWrite(Bin, nBytes)
File.Close()

Gui, Add, Picture, w256 h256, ahkiconnew.png
Gui, Show
Return ;    // end of auto-execcute section //




Base64Dec( ByRef B64, ByRef Bin ) {  ; By SKAN / 18-Aug-2017
Local Rqd := 0, BLen := StrLen(B64)                 ; CRYPT_STRING_BASE64 := 0x1
  DllCall( "Crypt32.dll\CryptStringToBinary", "Str",B64, "UInt",BLen, "UInt",0x1
         , "UInt",0, "UIntP",Rqd, "Int",0, "Int",0 )
  VarSetCapacity( Bin, 128 ), VarSetCapacity( Bin, 0 ),  VarSetCapacity( Bin, Rqd, 0 )
  DllCall( "Crypt32.dll\CryptStringToBinary", "Str",B64, "UInt",BLen, "UInt",0x1
         , "Ptr",&Bin, "UIntP",Rqd, "Int",0, "Int",0 )
Return Rqd
}

Testing Base64 encoded image in WEB control. ( tested and works in Win XP IE6 )

Code: Select all

#NoEnv
#Warn
#SingleInstance, Force

Base64ImageData := "
( LTrim Join
  iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAMAAABrrFhUAAAAz1BMVEX///8AAAD7/fwjdCv///+bwJ8SaBv///////9KjFBon26U
  u5j///////////////////////9Oj1VfmmX///////////////8NZRb4+PgJQw4MYBUJRw8MXRTP2dAKTBAJSBCguKJnf2nP1M+g
  raELWBNokmsLVBIKThEKUBEMWxMLUhILVhMJShDu8O7a4NotcTLk6eTE0cW4wrmUr5aHpolXh1uUopSGmIdWclhEfUgrVS3Ey8St
  wK6st614nHp3i3hCZES5ybosZDCUqpV0X6tXAAAAGHRSTlOzALL2jMz9TRXm3M6deVosJiHk35h1W1hTCYFzAAAIt0lEQVR42uzW
  SQrDMAxA0V/ZTpx5oCG6/0kLbkM6nSDSX2mrBwJxM54DnGOut164fHLf6vwHYI4YKs7fADvG2j8AlghIWkOll68KaxIgLm8AEUhB
  zRQSEE+AEaRVU7UC4w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LJsQMA931lpg/PQ2AA+ugBbEwAhA+sDA6g7eMABaAAegQQSwZI
  CScxMsAE1j5aJrK/N/jGW44jAcAfyaEAwNejGTLAlgewQflDCH4RHnEeCsMPNNWxP7T0h7NBo2ofLyveVnWEJ0LwIYjz+mR5rEw5
  tyD04/W38W3/8pcp1DxzBsDEPll6Fd94IFo9kELNU3K1/o2uI+wSAwus9TLBQsPO6Vb9Zoh+jpC2TS417+plloU/evaXhoDmn/XD
  B+B+AM34e9aD97yuHz8fL2f+mV7GtGfgDggAaMbHOiF1kiz/ar6qHz/WR9bowPqrA0GL+kUANGMxz13GKKWMHY66ftY8dowoyA/f
  Hcj1Ks68zRurIgBFLD9wzMZr8nZYN48fYxHaZqMDTuBbWosIAhQ9iALbMas4duAjlM/pgN/oQNSyA4IARQxrMfPD+Xz+eRYKQvmA
  DkQCHeAAwGJ8RZMVgfYbAKOMAlAACkABKAAFoAAUgAJQAApAG2UUgAL41269oEAMwgAQnUStutZ+6FK8/0m3WIp32HTICR4k5AV4
  AV6AaxSmZrAJtAN8wTWDOZg7QIXcDJahdoAIpRmsQOwACdTgDjiF1AHEQ2jmCuDlBliBTzPWB1g7wNUJejRTHQqnPADigWDoDrgA
  eBkAuwe0ZGfgI5pcLgr4fQBcLRhrkTtE7jaPofwmA+ApxTorf5/ONSaRAWA88wA/FYbIdxzaJjsAAAAASUVORK5CYII=
)" 

Gui, Add, ActiveX, w300 h300 vDoc, HtmlFile
Doc.Write( "<img src=""data:image/png;base64, " Base64ImageData """/>" )
Gui, Show,, ActiveX Base64 Image Test
Return

The image used in above examples:
http://i.imgur.com/dS56Ewu.png (2543 bytes)
Image
Also see: Base64ToComByteArray() :: Include image in script and display it with WIA 2.0
burque505
Posts: 961
Joined: 22 Jan 2017, 19:37

Re: Base64 encoder/decoder for Binary data

17 Aug 2017, 14:59

Thank you, SKAN.
Tested on Win7 x64, AHK_H 1.25.02, all three scripts work perfectly.
Regards,
burque505
burque505
Posts: 961
Joined: 22 Jan 2017, 19:37

Re: Base64 encoder/decoder for Binary data

19 Aug 2017, 18:05

GeekDude, thanks for that too!
burque505
User avatar
jNizM
Posts: 2414
Joined: 30 Sep 2013, 01:33
GitHub: jNizM
Contact:

Re: Base64 encoder/decoder for Binary data

05 Sep 2017, 07:42

Just for reference base64.ahk (GitHub) (Unicode / UTF-8 - like online tools does)
[AHK] 1.1.30.01 x64 Unicode | [WIN] 10 Pro (Version 1803) x64 | [GitHub] Profile
Donations are appreciated if I could help you
HillaryDev

Re: Base64 encoder/decoder for Binary data

06 Apr 2018, 10:39

can anyone explain why when I output the base 64 to a edit box on my gui it leaves spaces in between each line?
iseahound
Posts: 408
Joined: 13 Aug 2016, 21:04
GitHub: iseahound

Re: Base64 encoder/decoder for Binary data

08 Apr 2018, 15:33

On the Documentation page it says that for the 3rd parameter:

Code: Select all

0x00000001    CRYPT_STRING_BASE64    Base64, without headers.
0x40000000    CRYPT_STRING_NOCRLF    Do not append any new line characters to the encoded string. The default behavior is to use a carriage return/line feed (CR/LF) pair (0x0D/0x0A) to represent a new line.
So change the 0x1 in two DllCall to 0x40000001 DllCall( "Crypt32.dll\CryptBinaryToString", "Ptr",&Bin, "UInt",nBytes, "UInt",0x40000001, "Str",B64, "UIntP",Rqd )

Why is that the default behavior? Only Microsoft knows.
User avatar
jeeswg
Posts: 6395
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Base64 encoder/decoder for Binary data

08 Apr 2018, 15:44

Do note this re. CRYPT_STRING_NOCRLF:
CryptBinaryToString function (Windows)
https://msdn.microsoft.com/en-us/librar ... s.85).aspx
Windows Server 2003 and Windows XP: This value is not supported.
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
HillaryDev

Re: Base64 encoder/decoder for Binary data

08 Apr 2018, 16:40

iseahound wrote:On the Documentation page it says that for the 3rd parameter:

Code: Select all

0x00000001    CRYPT_STRING_BASE64    Base64, without headers.
0x40000000    CRYPT_STRING_NOCRLF    Do not append any new line characters to the encoded string. The default behavior is to use a carriage return/line feed (CR/LF) pair (0x0D/0x0A) to represent a new line.
So change the 0x1 in two DllCall to 0x40000001 DllCall( "Crypt32.dll\CryptBinaryToString", "Ptr",&Bin, "UInt",nBytes, "UInt",0x40000001, "Str",B64, "UIntP",Rqd )

Why is that the default behavior? Only Microsoft knows.

When I output the base64 to a text box (not edit box, just text lable that is not single line) it adds big spaces between each line even after updating the dllcall :thumbdown:
Ralf28

Re: Base64 encoder/decoder for Binary data

02 Jun 2018, 16:48

I get an error when I want a .png file decode

-----------------------------------------------

Error at Line 5.

Error: Continuation section too long.

-----------------------------------------------

It is a png. with the pixel size "900x505"

Does anyone know what this is and how to fix it that works?

Return to “Scripts and Functions”

Who is online

Users browsing this forum: robodesign and 34 guests