WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

Binary Operations

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Base64ToBinary Converts Base 64 String to Binary

 Keywords: CryptStringToBinary Base64ToBinary convert base 64 string  binary Crypt32.dll 


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Base64ToBinary - converts base 64 string to binary
;;
;; Parameters: strBase64 - (in) base 64 formatted string
;;             phBinary  - (in/out) pointer to variable
;;                         contains handle to binary buffer
;;                         on success.
;;
;; return: 0 on success otherwise system error number
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#DefineFunction Base64ToBinary(strBase64, phBinary)
   *phBinary = 0
   CRYPT_STRING_BASE64 = 1
   hCrypt  = DllLoad(DirWindows(1):"Crypt32.dll")
   hByteCount = BinaryAlloc(4)

   ; Get the binary buffer size
   bResult = DllCall(hCrypt, long:"CryptStringToBinaryA",lpstr:strBase64, long:0, long:CRYPT_STRING_BASE64, lpnull, lpbinary:hByteCount, lpnull, lpnull)
   If !bResult
      BinaryFree(hByteCount)
      DllFree(hCrypt)
      Return DllLastError()
   EndIf

   BinaryEodSet( hByteCount, 4 )
   nConvertedBytes = BinaryPeek4(hByteCount, 0)
   hConverted = BinaryAlloc(nConvertedBytes)

   ; Convert the string
   bResult = DllCall(hCrypt, long:"CryptStringToBinaryA",lpstr:strBase64, long:0, long:CRYPT_STRING_BASE64, lpbinary:hConverted, lpbinary:hByteCount, lpnull, lpnull)
   If !bResult Then nReturn = DllLastError()
   Else nReturn = 0

   BinaryFree(hByteCount)
   DllFree(hCrypt)
   BinaryEodSet(hConverted, nConvertedBytes)
   *phBinary = hConverted

   Return nReturn  ; 0 on success otherwise system error
#EndFunction

; Test

; Saved base 64 string as file to avoid
; waiting for web site to respond during testing.
retVar = FileGet(DirScript():"barcode.txt")
strOutFile = DirScript():"barcode.png"
If FileExist(strOutFile) Then FileDelete(strOutFile)

If Base64ToBinary(RetVar, &hResult) == 0
   BinaryWrite( hResult, strOutFile)
   BinaryFree(hResult)
EndIf

; View the result.
Run(strOutFile, "")
Exit

Article ID:   W18344
Filename:   Base64ToBinary Converts Base 64 String to Binary.txt
File Created: 2011:11:01:09:35:04
Last Updated: 2011:11:01:09:35:04