123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143 |
- #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
- using System;
- using Org.BouncyCastle.Crypto.Parameters;
- using Org.BouncyCastle.Utilities;
- namespace Org.BouncyCastle.Crypto.Engines
- {
- public class RC4Engine
- : IStreamCipher
- {
- private readonly static int STATE_LENGTH = 256;
-
- private byte[] engineState;
- private int x;
- private int y;
- private byte[] workingKey;
-
- public virtual void Init(
- bool forEncryption,
- ICipherParameters parameters)
- {
- if (parameters is KeyParameter)
- {
-
- workingKey = ((KeyParameter)parameters).GetKey();
- SetKey(workingKey);
- return;
- }
- throw new ArgumentException("invalid parameter passed to RC4 init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
- }
- public virtual string AlgorithmName
- {
- get { return "RC4"; }
- }
- public virtual byte ReturnByte(
- byte input)
- {
- x = (x + 1) & 0xff;
- y = (engineState[x] + y) & 0xff;
-
- byte tmp = engineState[x];
- engineState[x] = engineState[y];
- engineState[y] = tmp;
-
- return (byte)(input ^ engineState[(engineState[x] + engineState[y]) & 0xff]);
- }
- public virtual void ProcessBytes(
- byte[] input,
- int inOff,
- int length,
- byte[] output,
- int outOff)
- {
- Check.DataLength(input, inOff, length, "input buffer too short");
- Check.OutputLength(output, outOff, length, "output buffer too short");
- for (int i = 0; i < length ; i++)
- {
- x = (x + 1) & 0xff;
- y = (engineState[x] + y) & 0xff;
-
- byte tmp = engineState[x];
- engineState[x] = engineState[y];
- engineState[y] = tmp;
-
- output[i+outOff] = (byte)(input[i + inOff]
- ^ engineState[(engineState[x] + engineState[y]) & 0xff]);
- }
- }
- public virtual void Reset()
- {
- SetKey(workingKey);
- }
-
- private void SetKey(
- byte[] keyBytes)
- {
- workingKey = keyBytes;
-
- x = 0;
- y = 0;
- if (engineState == null)
- {
- engineState = new byte[STATE_LENGTH];
- }
-
- for (int i=0; i < STATE_LENGTH; i++)
- {
- engineState[i] = (byte)i;
- }
- int i1 = 0;
- int i2 = 0;
- for (int i=0; i < STATE_LENGTH; i++)
- {
- i2 = ((keyBytes[i1] & 0xff) + engineState[i] + i2) & 0xff;
-
- byte tmp = engineState[i];
- engineState[i] = engineState[i2];
- engineState[i2] = tmp;
- i1 = (i1+1) % keyBytes.Length;
- }
- }
- }
- }
- #endif
|