Home > Net >  Trying to make a function as robust as a website (BASE64)
Trying to make a function as robust as a website (BASE64)

Time:10-12

If I give this site https://www.base64decode.org/ data like NnFjamFvOGw5NnA1Y2Y2MHNtamlxb2drNzVfMjAyMTEwMjFUMTcwMDAwWiB

I get a result like 6qcjao8l96p5cf60smjiqogk75_20211021T170000Z

if I run the following PS lines

$Encoding = 'default'
$Result = [System.Text.Encoding]:: $Encoding.GetString([System.Convert]::FromBase64String('NnFjamFvOGw5NnA1Y2Y2MHNtamlxb2drNzVfMjAyMTEwMjFUMTcwMDAwWiB'))

I get error

Exception calling "FromBase64String" with "1" argument(s): "Invalid length for a Base-64 char array 
or string."
At line:1 char:1
  $Result = [System.Text.Encoding]:: $Encoding.GetString([System.Conver ...
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      FullyQualifiedErrorId : FormatException

I even tried to pad the line which sometimes works and sometimes doesn't depending on the line. (I am unsure why the padding is not always working)

function Get-PaddingRequired {
            param (
                [Parameter(Mandatory = $true)]
                [String]$InputString
            )
            $modulo = ($InputString.Length % 3)
       
            switch ($modulo) {
                0 { $paddingRequired = $null }
                1 { $paddingRequired = '==' }
                2 { $paddingRequired = '=' }
            }
            Return [string]$paddingRequired
        }

Running NnFjamFvOGw5NnA1Y2Y2MHNtamlxb2drNzVfMjAyMTEwMjFUMTcwMDAwWiB in my padding function above. I sadly only get one = the correct answer seems to be == which is confusing.

There should be a better way to become more robust like the site https://www.base64decode.org/. Ideas ?

CodePudding user response:

The main problem with your code is caused by a simple typo

Remove the space you have in front of $Encoding here:

$Result = [System.Text.Encoding]:: $Encoding.GetString([System.Convert]::FromBase64String(...))
#                                 ^
  • Related