rc4.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. *
  19. * File: rc4.c
  20. *
  21. * Purpose:
  22. *
  23. * Functions:
  24. *
  25. * Revision History:
  26. *
  27. * Author: Kyle Hsu
  28. *
  29. * Date: Sep 4, 2002
  30. *
  31. */
  32. #include "rc4.h"
  33. void rc4_init(PRC4Ext pRC4, unsigned char *pbyKey, unsigned int cbKey_len)
  34. {
  35. unsigned int ust1, ust2;
  36. unsigned int keyindex;
  37. unsigned int stateindex;
  38. unsigned char *pbyst;
  39. unsigned int idx;
  40. pbyst = pRC4->abystate;
  41. pRC4->ux = 0;
  42. pRC4->uy = 0;
  43. for (idx = 0; idx < 256; idx++)
  44. pbyst[idx] = (unsigned char)idx;
  45. keyindex = 0;
  46. stateindex = 0;
  47. for (idx = 0; idx < 256; idx++) {
  48. ust1 = pbyst[idx];
  49. stateindex = (stateindex + pbyKey[keyindex] + ust1) & 0xff;
  50. ust2 = pbyst[stateindex];
  51. pbyst[stateindex] = (unsigned char)ust1;
  52. pbyst[idx] = (unsigned char)ust2;
  53. if (++keyindex >= cbKey_len)
  54. keyindex = 0;
  55. }
  56. }
  57. unsigned int rc4_byte(PRC4Ext pRC4)
  58. {
  59. unsigned int ux;
  60. unsigned int uy;
  61. unsigned int ustx, usty;
  62. unsigned char *pbyst;
  63. pbyst = pRC4->abystate;
  64. ux = (pRC4->ux + 1) & 0xff;
  65. ustx = pbyst[ux];
  66. uy = (ustx + pRC4->uy) & 0xff;
  67. usty = pbyst[uy];
  68. pRC4->ux = ux;
  69. pRC4->uy = uy;
  70. pbyst[uy] = (unsigned char)ustx;
  71. pbyst[ux] = (unsigned char)usty;
  72. return pbyst[(ustx + usty) & 0xff];
  73. }
  74. void rc4_encrypt(PRC4Ext pRC4, unsigned char *pbyDest,
  75. unsigned char *pbySrc, unsigned int cbData_len)
  76. {
  77. unsigned int ii;
  78. for (ii = 0; ii < cbData_len; ii++)
  79. pbyDest[ii] = (unsigned char)(pbySrc[ii] ^ rc4_byte(pRC4));
  80. }