Help deciphering powershell code

Welcome Forums General PowerShell Q&A Help deciphering powershell code

This topic contains 4 replies, has 4 voices, and was last updated by

5 years, 5 months ago.

  • Author
  • #9658

    Points: 0
    Rank: Member

    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[$_]


  • #9664

    Points: 0
    Rank: Member

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

  • #9665

    Points: 1
    Rank: Member

    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. 🙂

    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]
  • #9666

    Points: 0
    Rank: Member

    Ah, the old "a cat walked across my keyboard" approach to software development. 😀

    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 } )

  • #9667

    Points: 1
    Rank: Member

    For the record, the comments were added for the forum reader. 🙂

    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.

The topic ‘Help deciphering powershell code’ is closed to new replies.