Help deciphering powershell code

Can you please help me decipher the following code:

0…0xff | %{ $i=0 } { $i = ($i + $b[$] + $keySeed[$]) -band 0xff; $b[$],$b[$i] = $b[$i],$b[$] }

I am trying to convert to C# .net. I understand the code until this: $b[$],$b[$i] = $b[$i],$b[$]


This is how you “swap” two values.
$b[$] takes on the value of $b[$i]
$b[$i] takes on the original value of $b[$

The section you highlighted ($b[$],$b[$i] = $b[$i],$b[$]) will swap two values in array $b: the one at index $_ with the one at index $i.

Also for reference if others are curious, this snippet comes from here: Just because it’s in a function to decrypt some data though doesn’t mean it has to be quite so cryptic. :slight_smile:

Below is another version of the same script, expanded out a little. I haven’t tried it but I believe it will do the same thing.

for ($i = $j = 0; $i -lt 256; $i++) {

    # I didn't figure out what keySeed and b were for, so I can't really comment on this line
    $j += $b[$i] + $keySeed[$i]

    # Make sure $j is less than or equal to 255 (0xff) by stripping off the higher bits so that it continues to be a valid index into our array
    $j = $j -band 0xff

    # Swap $b[$i] with $b[$j]
    $b[$i],$b[$j] = $b[$j],$b[$i]

Ah, the old “a cat walked across my keyboard” approach to software development. :smiley:

Poshoholic’s version is better, though in production code I wouldn’t even bother with the comments. It’s pretty self-documenting as is, now that you can actually read it. One statement per line, people! (Possible exceptions being very simple conditionals, like if (-not $success) { return } )

For the record, the comments were added for the forum reader. :slight_smile:

I wouldn’t put those comments in my scripts either, unless it was some particularly obscure piece of logic that I wanted to explain or some note that I wanted others to be aware of when reading the code. I do advocate for using regions in code though, breaking scripts down into business logic and identifying what each chunk does. That makes it easier for someone else to follow later.