0

The following code is not correctly encoding long strings to Base64. What can I do to fix this?

Input: The quick brown fox jumps over the lazy dog

Expected output: VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw==

Actual output: VGhl

Param(
  [string]$stringToEncode
)

$encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($stringToEncode))

Write-Host $encoded
3
  • 2
    Use quotes, as your string contains spaces. Commented Sep 23, 2015 at 9:37
  • Just tried it from the command line: and it works. Therefore there is something else going on. I suspect the value of $stringToEncode is not what you think it is (try adding a Write-Debug and enabling debug output). Commented Sep 23, 2015 at 9:44
  • @Richard PetSerAl already pointed it out: the input most likely is passed on the command line as The quick brown fox jumps over the lazy dog (without quotes) not as a single string "The quick brown fox jumps over the lazy dog" (with quotes). Thus only The is passed into $stringToEncode (VGhl == The). Commented Sep 23, 2015 at 9:49

1 Answer 1

1

"VGhl" is the base64-encoded form of the word "The". Most likely you're calling the script like this:

C:\path\to\your.ps1 The quick brown fox jumps over the lazy dog

Without quotes each word is parsed as a separate argument, so only the first word ends up in the parameter $stringToEncode. To avoid this put quotes around the sentence, so it's passed as a single argument:

C:\path\to\your.ps1 "The quick brown fox jumps over the lazy dog"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.