www.pudn.com > encryption.rar > DES.java


/*
Christoforos Pirillos @ Villanova University - May 1999
based on code from the book "Java Network Programming" by Hughes
*/

package encryption;

/**An implementation of DES, the Data Encryption Standard. DES uses some
fairly complicated transformations and permutations; they are implemented
by the DEA class. */

public class DES extends Cipher {

protected long keys[];

/**Accepts a 56-bit key and generates a key schedule that is used in the
encryption process.*/

public DES (long key) {
	keys = DEA.makeKeys (key);
}
/**Accepts a byte[8] of plaintext and converts it into a byte[8] of
cipher*/
public void encipherBlock (byte[] plain, int po, byte[] cipher, int co) {
	long plainText = Crypt.bytesToLong (plain, po);
	long cipherText = encrypt (plainText);
	Crypt.longToBytes (cipherText, cipher, co);
}

/**Does the reverse of encipherBlock*/
public void decipherBlock (byte[] cipher, int co, byte[] plain, int po) {
	long cipherText = Crypt.bytesToLong (cipher, co);
	long plainText = decrypt (cipherText);
	Crypt.longToBytes (plainText, plain, po);
}

/**Returns the blocksize of the cipher (8 bytes)*/
public int blockSize () {
	return 8;
}
/**The actual DES encryption happens here.*/
public final long encrypt (long w) {
	long[] keys = this.keys;
	long x = DEA.initialPerm (w);
	int l = (int) (x >>> 32);
	int r = (int) x;
	for (int i =0; i<16; ++i) {
		int tmp = DEA.desFunc (r, keys[i]) ^ l;
		l = r;
		r = tmp;
	}
	long y = ((long) r << 32) | ((long) l & 0xffffffffL);
	return DEA.finalPerm (y);
}

/**The reverse of encrypt*/
public final long decrypt (long w) {
	long[] keys = this.keys;
	long x = DEA.initialPerm(w);	
	int l = (int) (x >>> 32);
	int r = (int) x;
	for (int i =15; i>=0; --i) {
		int tmp = DEA.desFunc (r, keys[i]) ^ l;
		l = r;
		r = tmp;
	}
	long y = ((long) r << 32) | ((long) l & 0xffffffffL);
	return DEA.finalPerm (y);
}

/**Performs the XOR operations necessary to compute parity in the low bit
of every byte in the supplied key*/

public static long paritySet (long key) {
        long pKey =
                (key>>1)^(key>>2)^(key>>3)^(key>>4)^(key>>5)^(key>>6)^(key>>7);
        return (key | 0x0101010101010101L)^( pKey & 0x0101010101010101L);
}

/**Verifies that the key is the same after parity is set, and is therefore
correct*/
                
public static boolean isParity (long key) {
        return (key==paritySet(key));
}

} /* end of class DES*/