Last active
November 12, 2019 05:04
-
-
Save daopk/4111e583735e08c5fa23 to your computer and use it in GitHub Desktop.
rc4 algorithm in php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class RC4 | |
{ | |
public static $_key = 'aRand0mStr1ng'; | |
public static function encode($string, $key = null) | |
{ | |
$res = self::_rc4($string, $key); | |
$encrypted = unpack('H*', $res); | |
if (!empty($encrypted)) return array_values($encrypted)[0]; | |
return ''; | |
} | |
public static function decode($string, $key = null) | |
{ | |
if (ctype_xdigit($string)) { | |
$str = pack('H*', $string); | |
return self::_rc4($str, $key); | |
} else { | |
return ''; | |
} | |
} | |
public static function _rc4($str, $key = null) | |
{ | |
if(!$key) $key = self::$_key; | |
$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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment