jesobreira

RC4 and SHA256 PHP

Oct 27th, 2015
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.24 KB | None | 0 0
  1. <?php
  2.  
  3. /* Usage:
  4.  
  5. Para SHA-256 (irreversível):
  6.  
  7. echo encrypt("string a ser criptografada");
  8.  
  9.  
  10. Para codificar RC4 (reversível):
  11.  
  12. echo encode('hello world', 'senha');
  13.  
  14. Para decodificar (a senha precisa ser a mesma utilizada para criptografar):
  15.  
  16. echo encode('a7a8a2v2a1', 'senha'); // escrevi aleatoriamente essa hash aí
  17.  
  18.  
  19. */
  20.  
  21. function encrypt($str) { // one way
  22.     return hash('sha256', $str);
  23. }
  24.  
  25. function encode($str, $key = null) { // two way
  26.     return str2hex(_rc4($str, $key));
  27. }
  28.  
  29. function decode($str, $key = null) {
  30.     return _rc4(hex2str($str), $key);
  31. }
  32.  
  33. function hex2str( $hex ) {
  34.   return pack('H*', $hex);
  35. }
  36.  
  37. function str2hex( $str ) {
  38.   return array_shift( unpack('H*', $str) );
  39. }
  40.  
  41. function _rc4($str, $key=null) { // internal
  42.     $s = array();
  43.     for ($i = 0; $i < 256; $i++) {
  44.         $s[$i] = $i;
  45.     }
  46.     $j = 0;
  47.     for ($i = 0; $i < 256; $i++) {
  48.         $j = ($j + $s[$i] + ord($key[$i % strlen($key)])) % 256;
  49.         $x = $s[$i];
  50.         $s[$i] = $s[$j];
  51.         $s[$j] = $x;
  52.     }
  53.     $i = 0;
  54.     $j = 0;
  55.     $res = '';
  56.     for ($y = 0; $y < strlen($str); $y++) {
  57.         $i = ($i + 1) % 256;
  58.         $j = ($j + $s[$i]) % 256;
  59.         $x = $s[$i];
  60.         $s[$i] = $s[$j];
  61.         $s[$j] = $x;
  62.         $res .= $str[$y] ^ chr($s[($s[$i] + $s[$j]) % 256]);
  63.     }
  64.     return $res; // RC4
  65. }
Add Comment
Please, Sign In to add comment