home *** CD-ROM | disk | FTP | other *** search
/ PSION CD 2 / PsionCDVol2.iso / Programs / 720 / PDF090B4-SorceCode / pdf / rc4.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-30  |  1.7 KB  |  81 lines

  1. /************************************************************************
  2.  *                                    *
  3.  * RC4 Encryption Algorithm                         *
  4.  * Copyright Peter Gutmann 1995-1996                    *
  5.  *                                    *
  6.  ************************************************************************/
  7.  
  8. // Ported to EPOC by Sander van der Wal
  9. // Copyright (c) 2000 Sander van der Wal
  10. //
  11. // $Id: rc4.cpp 1.1 2000-09-17 13:39:37+02 svdwal Exp svdwal $
  12. //
  13. // $Log: rc4.cpp $
  14. // Revision 1.1  2000-09-17 13:39:37+02  svdwal
  15. // Initial checkin
  16. //
  17.  
  18. /* Optimized RC4 code, from an unknown source ("and they knew not from whence
  19.    it had come...") */
  20.  
  21. #include "rc4.h"
  22.  
  23. void
  24. rc4ExpandKey( RC4KEY *rc4, unsigned char const *key, int keylen )
  25. {
  26.     int x, keypos = 0;
  27.     rc4word sx, y = 0;
  28.     rc4word *state = &rc4->state[ 0 ];
  29.  
  30.     rc4->x = rc4->y = 0;
  31.  
  32.     for( x = 0; x < 256; x++ )
  33.         state[ x ] = x;
  34.  
  35.     for( x = 0; x < 256; x++ )
  36.         {
  37.         sx = state[ x ];
  38.         y += sx + key[ keypos ];
  39. #ifdef USE_LONG_RC4
  40.         y &= 0xFF;
  41. #endif /* USE_LONG_RC4 */
  42.         state[ x ] = state[ y ];
  43.         state[ y ] = sx;
  44.  
  45.         if( ++keypos == keylen )
  46.             keypos = 0;
  47.         }
  48.     }
  49.  
  50. void
  51. rc4Crypt( RC4KEY *rc4, unsigned char *data, int len )
  52. {
  53.     rc4word x = rc4->x, y = rc4->y;
  54.     rc4word sx, sy;
  55.     rc4word *state = &rc4->state[ 0 ];
  56.  
  57.     while (len--) {
  58.         x++;
  59. #ifdef USE_LONG_RC4
  60.         x &= 0xFF;
  61. #endif /* USE_LONG_RC4 */
  62.         sx = state[ x ];
  63.         y += sx;
  64. #ifdef USE_LONG_RC4
  65.         y &= 0xFF;
  66. #endif /* USE_LONG_RC4 */
  67.         sy = state[ y ];
  68.         state[ y ] = sx;
  69.         state[ x ] = sy;
  70.  
  71. #ifdef USE_LONG_RC4
  72.         *data++ ^= state[ ( unsigned char ) ( sx+sy ) ];
  73. #else
  74.         *data++ ^= state[ ( sx+sy ) & 0xFF ];
  75. #endif /* USE_LONG_RC4 */
  76.     }
  77.  
  78.     rc4->x = x;
  79.     rc4->y = y;
  80. }
  81.