newspaint

Documenting Problems That Were Difficult To Find The Answer To

Monthly Archives: October 2019

PowerShell XOR Strings

PowerShell lacks the ability to XOR strings together. In Perl this is trivial:

$ perl -e "print( '1234' ^ 'aaaa' )"
PSRU

$ perl -e "print( 'PSRU' ^ 'aaaa' )"
1234

$ perl -e "print( 'PSRU' ^ '1234' )"
aaaa

A custom C# .Net class can be in-line compiled into PowerShell, however, which will perform a similar function:

Add-Type @'
  public class MyXORString {
    public static System.String XORString(
      System.String source
      ,System.String key
    ) {
      System.Text.StringBuilder sb = new System.Text.StringBuilder();
      System.Int32 sourceLen = source.Length;
      System.Int32 keyLen = key.Length;
      System.Int32 sourceIdx = 0;
      System.Int32 keyIdx = 0;
      System.Char workingChar;
      while ( sourceIdx < sourceLen ) {
        workingChar = (System.Char)( source[sourceIdx] ^ key[keyIdx] );
        sb.Append( workingChar );

        sourceIdx += 1;
        keyIdx += 1;
        if ( keyIdx >= keyLen ) {
          keyIdx = 0;
        }
      }

      return sb.ToString();
    }
  }
'@

[MyXORString]::XORString( "1234", "aaaa" ); # outputs PSRU
[MyXORString]::XORString( "PSRU", "aaaa" ); # outputs 1234
[MyXORString]::XORString( "PSRU", "1234" ); # outputs aaaa

# Note that the key will repeat if shorter than the source
[MyXORString]::XORString( "1234", "a" ); # outputs PSRU
[MyXORString]::XORString( "PSRU", "a" ); # outputs 1234