1 19 20 package com.maverick.crypto.engines; 21 22 public class RC4Engine 23 { 24 private final static int STATE_LENGTH = 256; 25 26 30 31 private byte[] engineState = null; 32 private int x = 0; 33 private int y = 0; 34 private byte[] workingKey = null; 35 36 44 public void init( 45 boolean forEncryption, 46 byte[] key 47 ) 48 { 49 54 workingKey = key; 55 setKey(workingKey); 56 return; 57 } 58 59 public String getAlgorithmName() 60 { 61 return "RC4"; 62 } 63 64 public byte returnByte(byte in) 65 { 66 x = (x + 1) & 0xff; 67 y = (engineState[x] + y) & 0xff; 68 69 byte tmp = engineState[x]; 71 engineState[x] = engineState[y]; 72 engineState[y] = tmp; 73 74 return (byte)(in ^ engineState[(engineState[x] + engineState[y]) & 0xff]); 76 } 77 78 public void processBytes( 79 byte[] in, 80 int inOff, 81 int len, 82 byte[] out, 83 int outOff 84 ) 85 { 86 if ((inOff + len) > in.length) 87 { 88 throw new RuntimeException ("input buffer too short"); 89 } 90 91 if ((outOff + len) > out.length) 92 { 93 throw new RuntimeException ("output buffer too short"); 94 } 95 96 for (int i = 0; i < len ; i++) 97 { 98 x = (x + 1) & 0xff; 99 y = (engineState[x] + y) & 0xff; 100 101 byte tmp = engineState[x]; 103 engineState[x] = engineState[y]; 104 engineState[y] = tmp; 105 106 out[i+outOff] = (byte)(in[i + inOff] 108 ^ engineState[(engineState[x] + engineState[y]) & 0xff]); 109 } 110 } 111 112 public void reset() 113 { 114 setKey(workingKey); 115 } 116 117 119 private void setKey(byte[] keyBytes) 120 { 121 workingKey = keyBytes; 122 123 125 x = 0; 126 y = 0; 127 128 if (engineState == null) 129 { 130 engineState = new byte[STATE_LENGTH]; 131 } 132 133 for (int i=0; i < STATE_LENGTH; i++) 135 { 136 engineState[i] = (byte)i; 137 } 138 139 int i1 = 0; 140 int i2 = 0; 141 142 for (int i=0; i < STATE_LENGTH; i++) 143 { 144 i2 = ((keyBytes[i1] & 0xff) + engineState[i] + i2) & 0xff; 145 byte tmp = engineState[i]; 147 engineState[i] = engineState[i2]; 148 engineState[i2] = tmp; 149 i1 = (i1+1) % keyBytes.length; 150 } 151 } 152 } 153 | Popular Tags |