RC4.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * PHPExcel_Reader_Excel5_RC4
  4. *
  5. * Copyright (c) 2006 - 2015 PHPExcel
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * @category PHPExcel
  22. * @package PHPExcel_Reader_Excel5
  23. * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
  24. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  25. * @version ##VERSION##, ##DATE##
  26. */
  27. class PHPExcel_Reader_Excel5_RC4
  28. {
  29. // Context
  30. protected $s = array();
  31. protected $i = 0;
  32. protected $j = 0;
  33. /**
  34. * RC4 stream decryption/encryption constrcutor
  35. *
  36. * @param string $key Encryption key/passphrase
  37. */
  38. public function __construct($key)
  39. {
  40. $len = strlen($key);
  41. for ($this->i = 0; $this->i < 256; $this->i++) {
  42. $this->s[$this->i] = $this->i;
  43. }
  44. $this->j = 0;
  45. for ($this->i = 0; $this->i < 256; $this->i++) {
  46. $this->j = ($this->j + $this->s[$this->i] + ord($key[$this->i % $len])) % 256;
  47. $t = $this->s[$this->i];
  48. $this->s[$this->i] = $this->s[$this->j];
  49. $this->s[$this->j] = $t;
  50. }
  51. $this->i = $this->j = 0;
  52. }
  53. /**
  54. * Symmetric decryption/encryption function
  55. *
  56. * @param string $data Data to encrypt/decrypt
  57. *
  58. * @return string
  59. */
  60. public function RC4($data)
  61. {
  62. $len = strlen($data);
  63. for ($c = 0; $c < $len; $c++) {
  64. $this->i = ($this->i + 1) % 256;
  65. $this->j = ($this->j + $this->s[$this->i]) % 256;
  66. $t = $this->s[$this->i];
  67. $this->s[$this->i] = $this->s[$this->j];
  68. $this->s[$this->j] = $t;
  69. $t = ($this->s[$this->i] + $this->s[$this->j]) % 256;
  70. $data[$c] = chr(ord($data[$c]) ^ $this->s[$t]);
  71. }
  72. return $data;
  73. }
  74. }