RC4.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Reader\Xls;
  3. class RC4
  4. {
  5. // Context
  6. protected $s = [];
  7. protected $i = 0;
  8. protected $j = 0;
  9. /**
  10. * RC4 stream decryption/encryption constrcutor.
  11. *
  12. * @param string $key Encryption key/passphrase
  13. */
  14. public function __construct($key)
  15. {
  16. $len = strlen($key);
  17. for ($this->i = 0; $this->i < 256; ++$this->i) {
  18. $this->s[$this->i] = $this->i;
  19. }
  20. $this->j = 0;
  21. for ($this->i = 0; $this->i < 256; ++$this->i) {
  22. $this->j = ($this->j + $this->s[$this->i] + ord($key[$this->i % $len])) % 256;
  23. $t = $this->s[$this->i];
  24. $this->s[$this->i] = $this->s[$this->j];
  25. $this->s[$this->j] = $t;
  26. }
  27. $this->i = $this->j = 0;
  28. }
  29. /**
  30. * Symmetric decryption/encryption function.
  31. *
  32. * @param string $data Data to encrypt/decrypt
  33. *
  34. * @return string
  35. */
  36. public function RC4($data)
  37. {
  38. $len = strlen($data);
  39. for ($c = 0; $c < $len; ++$c) {
  40. $this->i = ($this->i + 1) % 256;
  41. $this->j = ($this->j + $this->s[$this->i]) % 256;
  42. $t = $this->s[$this->i];
  43. $this->s[$this->i] = $this->s[$this->j];
  44. $this->s[$this->j] = $t;
  45. $t = ($this->s[$this->i] + $this->s[$this->j]) % 256;
  46. $data[$c] = chr(ord($data[$c]) ^ $this->s[$t]);
  47. }
  48. return $data;
  49. }
  50. }