$theTitle=wp_title(" - ", false); if($theTitle != "") { ?>
About Virtualization, VDI, SBC, Application Compatibility and anything else I feel like
For an upcoming blog post I needed to decrypt some data using the rc4 algorithm. I wanted to do this with PowerShell but sadly PowerShell and the .NET framework have no functions for it.
So I needed to implement it (download at the bottom of the post):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | function rc4 { param( [Byte[]]$data, [Byte[]]$key ) # Make a copy of the input data [Byte[]]$buffer = New-Object Byte[] $data.Length $data.CopyTo($buffer, 0) [Byte[]]$s = New-Object Byte[] 256; [Byte[]]$k = New-Object Byte[] 256; for ($i = 0; $i -lt 256; $i++) { $s[$i] = [Byte]$i; $k[$i] = $key[$i % $key.Length]; } $j = 0; for ($i = 0; $i -lt 256; $i++) { $j = ($j + $s[$i] + $k[$i]) % 256; $temp = $s[$i]; $s[$i] = $s[$j]; $s[$j] = $temp; } $i = $j = 0; for ($x = 0; $x -lt $buffer.Length; $x++) { $i = ($i + 1) % 256; $j = ($j + $s[$i]) % 256; $temp = $s[$i]; $s[$i] = $s[$j]; $s[$j] = $temp; [int]$t = ($s[$i] + $s[$j]) % 256; $buffer[$x] = $buffer[$x] -bxor $s[$t]; } return $buffer } |
And here is a usage example (the BinToHex and HexToBin functions are from my previous blog).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $enc = [System.Text.Encoding]::ASCII # The data we're going to encrypt [Byte[]]$data = $enc.GetBytes("Hello World!") # The key we're going to use [Byte[]]$key = $enc.GetBytes("SECRET") # Encryp the data, a byte array is returned $EncryptedBytes = rc4 $data $key # Convert the byte array into a hex string so we eg save it to disk $EncryptedString = BinToHex $EncryptedBytes # Now decrypt the data [Byte[]]$data = HexToBin $EncryptedString $DecryptedBytes = rc4 $data $key $DecryptedString = $enc.GetString($DecryptedBytes) |
One Response for "RC4 Encryption in PowerShell"
[…] I decided to do this in PowerShell because it would be a nice exercise (in fact, that’s why I wrote the rc4 function I published earlier). […]
Leave a reply