RC4.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // This code is derived from jcifs smb client library <jcifs at samba dot org>
  2. // Ported by J. Arturo <webmaster at komodosoft dot net>
  3. //
  4. // This library is free software; you can redistribute it and/or
  5. // modify it under the terms of the GNU Lesser General Public
  6. // License as published by the Free Software Foundation; either
  7. // version 2.1 of the License, or (at your option) any later version.
  8. //
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. // Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public
  15. // License along with this library; if not, write to the Free Software
  16. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. namespace SharpCifs.Util
  18. {
  19. public class Rc4
  20. {
  21. internal byte[] S;
  22. internal int I;
  23. internal int J;
  24. public Rc4()
  25. {
  26. }
  27. public Rc4(byte[] key)
  28. {
  29. Init(key, 0, key.Length);
  30. }
  31. public virtual void Init(byte[] key, int ki, int klen)
  32. {
  33. S = new byte[256];
  34. for (I = 0; I < 256; I++)
  35. {
  36. S[I] = unchecked((byte)I);
  37. }
  38. for (I = J = 0; I < 256; I++)
  39. {
  40. J = (J + key[ki + I % klen] + S[I]) & unchecked(0xff);
  41. byte t = S[I];
  42. S[I] = S[J];
  43. S[J] = t;
  44. }
  45. I = J = 0;
  46. }
  47. public virtual void Update(byte[] src, int soff, int slen, byte[] dst, int doff)
  48. {
  49. int slim;
  50. slim = soff + slen;
  51. while (soff < slim)
  52. {
  53. I = (I + 1) & unchecked(0xff);
  54. J = (J + S[I]) & unchecked(0xff);
  55. byte t = S[I];
  56. S[I] = S[J];
  57. S[J] = t;
  58. dst[doff++] = unchecked((byte)(src[soff++] ^ S[(S[I] + S[J]) & unchecked(0xff)]));
  59. }
  60. }
  61. }
  62. }