click On Me and See A Very Nice... Content..


View My Stats

Sunday, February 14, 2010

The RC4 algorithm

Listing 13-3: The RC4 algorithm

/**
* Method rc4
* Description: performs encryption
* and decryption
*
* @param in the in buffer
* @param inOffset any in offset
* @param inLen the length of the in buffer
* @param out the out buffer
* @param outOffset any out offset
*
*/
protected void rc4(byte[] in, int inOffset, int inLen,
byte[] out, int outOffset)
{
/*
* The byte is XORed with the plaintext to produce the ciphertext
* The byte is XORed with the ciphertext to produce the plaintext
* The algorithm is symmetric, meaning this function will work for both
* encryption and decryption
*/
int xorIndex, temp;
for (int i = 0; i <>
{
x = (x + 1) & 0xFF;
y = (sBox[x] + y) & 0xFF;
temp = sBox[x];
sBox[x] = sBox[y];
sBox[y] = temp;
xorIndex = (sBox[x] + sBox[y]) & 0xFF;
out[outOffset++] = (byte) (in[inOffset++]
^ sBox[xorIndex]);
}
}
/**
* Method prepare_key
* Description: initializes the key
*
*
* @param key the key that will set the S-box.
*
* @throws InvalidKeyException
*
*/
protected void prepare_key(Key key) throws InvalidKeyException
{
/*
* Fill the S-box with the key
* Key Setup
*/
byte[] userkey = key.getEncoded();
if (userkey == null)
{
throw new InvalidKeyException("Null user key");
}
int len = userkey.length;
if (len == 0)
{
throw new InvalidKeyException(
"Invalid user key length");
}
/*
* Reset x and y
*/
x = y = 0;
for (int index = 0; index <>
{
sBox[index] = index;
}
int index1 = 0, index2 = 0, temp;
for (int counter = 0; counter <>
{
index2 =
((userkey[index1] & 0xFF) + sBox[counter] + index2)
& 0xFF;
/*
* Swap the byte
*/
temp = sBox[counter];
sBox[counter] = sBox[index2];
sBox[index2] = temp;
index1 = (index1 + 1) % len;
}
}
}

No comments:

Post a Comment