Skip to content

Instantly share code, notes, and snippets.

@farhadi
Created March 24, 2012 17:09
Show Gist options
  • Save farhadi/2185197 to your computer and use it in GitHub Desktop.
Save farhadi/2185197 to your computer and use it in GitHub Desktop.
RC4 encryption in javascript and php
/*
* RC4 symmetric cipher encryption/decryption
*
* @license Public Domain
* @param string key - secret key for encryption/decryption
* @param string str - string to be encrypted/decrypted
* @return string
*/
function rc4(key, str) {
var s = [], j = 0, x, res = '';
for (var i = 0; i < 256; i++) {
s[i] = i;
}
for (i = 0; i < 256; i++) {
j = (j + s[i] + key.charCodeAt(i % key.length)) % 256;
x = s[i];
s[i] = s[j];
s[j] = x;
}
i = 0;
j = 0;
for (var y = 0; y < str.length; y++) {
i = (i + 1) % 256;
j = (j + s[i]) % 256;
x = s[i];
s[i] = s[j];
s[j] = x;
res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
}
return res;
}
<?php
/*
* RC4 symmetric cipher encryption/decryption
*
* @license Public Domain
* @param string key - secret key for encryption/decryption
* @param string str - string to be encrypted/decrypted
* @return string
*/
function rc4($key, $str) {
$s = array();
for ($i = 0; $i < 256; $i++) {
$s[$i] = $i;
}
$j = 0;
for ($i = 0; $i < 256; $i++) {
$j = ($j + $s[$i] + ord($key[$i % strlen($key)])) % 256;
$x = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $x;
}
$i = 0;
$j = 0;
$res = '';
for ($y = 0; $y < strlen($str); $y++) {
$i = ($i + 1) % 256;
$j = ($j + $s[$i]) % 256;
$x = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $x;
$res .= $str[$y] ^ chr($s[($s[$i] + $s[$j]) % 256]);
}
return $res;
}
?>
@jesobreira
Copy link

Here's my port to AutoIt3:

Func rc4($sKey, $sStr)
	Local $s[256], $j = 0, $x, $res, $y, $i
	Local $uBound
	For $i = 0 To 255
		$s[$i] = $i
	Next
	For $i = 0 To 255
		$j = Mod(($j + $s[$i] + Asc(StringMid($sKey, Mod($i, StringLen($sKey))+1, 1))), 256)
		$x = $s[$i]
		$s[$i] = $s[$j]
		$s[$j] = $x
	Next
	$i = 0
	$j = 0
	For $y = 0 To StringLen($sStr)-1
		$i = Mod(($i + 1), 256)
		$j = Mod(($j + $s[$i]), 256)
		$x = $s[$i]
		$s[$i] = $s[$j]
		$s[$j] = $x
		$res &= Chr(BitXOR(Asc(StringMid($sStr, $y+1, 1)), ($s[Mod(($s[$i] + $s[$j]), 256)])))
	Next
	Return $res
EndFunc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment