Base64: Difference between revisions
(Base 64 Encoder Function written in Native NSIS) |
(No difference)
|
Revision as of 01:40, 26 September 2008
BASE64 Encoding Function
As a result of needing to send data in a URL from my NSIS Installer, and because I didn't want to include another dependency, I wrote the below Base64 Encoder.
Usage is as follows:
${Base64_Encode} "THIS WILL BE ENCODED" Pop $0
- $0 now equals VEhJUyBXSUxMIEJFIEVOQ09ERUQ=
Also there is a variant for encoding in a URL safe form, ${Base64_URLEncode}, which just uses a different encodinging table, (but a standard one,) from the original version.
<highlight-nsis> !ifndef BASE64_NSH !define BASE64_NSH
!include registers.nsh !include specialstring.nsh
!define BASE64_ENCODINGTABLE "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" !define BASE64_ENCODINGTABLEURL "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
!define BASE64_PADDING "="
VAR OCTETVALUE VAR BASE64TEMP
!define Base64_Encode "!insertmacro Base64_Encode" !define Base64_URLEncode "!insertmacro Base64_URLEncode"
!macro Base64_Encode _cleartext ${SaveRegisters} push `${_cleartext}` push `${BASE64_ENCODINGTABLE}` Call Base64_Encode Pop $BASE64TEMP ${RestoreRegisters} Push $BASE64TEMP !macroend
!macro Base64_URLEncode _cleartext ${SaveRegisters} push `${_cleartext}` push `${BASE64_ENCODINGTABLEURL}` Call Base64_Encode Pop $BASE64TEMP ${RestoreRegisters} Push $BASE64TEMP !macroend
Function Base64_Encode pop $R2 ; Encoding table pop $R0 ; Clear Text StrCpy "$R1" "" # The result
StrLen $1 "$R0" StrCpy $0 0
${WHILE} $0 < $1 # Copy 3 characters, and for each character push their value. StrCpy $OCTETVALUE 0
StrCpy $5 $0 StrCpy $4 "$R0" 1 $5 ${CharToASCII} $4 "$4"
IntOp $OCTETVALUE $4 << 16
IntOp $5 $5 + 1 ${IF} $5 < $1 StrCpy $4 "$R0" 1 $5 ${CharToASCII} $4 "$4"
IntOp $4 $4 << 8 IntOp $OCTETVALUE $OCTETVALUE + $4
IntOp $5 $5 + 1 ${IF} $5 < $1 StrCpy $4 "$R0" 1 $5 ${CharToASCII} $4 "$4"
IntOp $OCTETVALUE $OCTETVALUE + $4 ${ENDIF} ${ENDIF}
# Now take the 4 indexes from the encoding table, based on 6bits each of the octet's value. IntOp $4 $OCTETVALUE >> 18 IntOp $4 $4 & 63 StrCpy $5 "$R2" 1 $4 StrCpy $R1 "$R1$5"
IntOp $4 $OCTETVALUE >> 12 IntOp $4 $4 & 63 StrCpy $5 "$R2" 1 $4 StrCpy $R1 "$R1$5"
StrCpy $6 $0 StrCpy $7 2
IntOp $6 $6 + 1 ${IF} $6 < $1 IntOp $4 $OCTETVALUE >> 6 IntOp $4 $4 & 63 StrCpy $5 "$R2" 1 $4 StrCpy $R1 "$R1$5" IntOp $7 $7 - 1 ${ENDIF}
IntOp $6 $6 + 1 ${IF} $6 < $1 IntOp $4 $OCTETVALUE & 63 StrCpy $5 "$R2" 1 $4 StrCpy $R1 "$R1$5" IntOp $7 $7 - 1 ${ENDIF}
# If there is any padding required, we now write that here. ${IF} $7 > 0 StrCpy $R1 "$R1${BASE64_PADDING}" ${ENDIF}
IntOp $0 $0 + 3 ${ENDWHILE}
Push "$R1"
FunctionEnd
!endif ;BASE64_NSH