DES Algorithm - Java Implementation
Part:
1
2
3
4
(Continued from previous part...)
private static byte[] selectBits(byte[] in, int pos, int len) {
int numOfBytes = (len-1)/8 + 1;
byte[] out = new byte[numOfBytes];
for (int i=0; i<len; i++) {
int val = getBit(in,pos+i);
setBit(out,i,val);
}
return out;
}
private static byte[] selectBits(byte[] in, int[] map) {
int numOfBytes = (map.length-1)/8 + 1;
byte[] out = new byte[numOfBytes];
for (int i=0; i<map.length; i++) {
int val = getBit(in,map[i]-1);
setBit(out,i,val);
}
return out;
}
private static int getBit(byte[] data, int pos) {
int posByte = pos/8;
int posBit = pos%8;
byte valByte = data[posByte];
int valInt = valByte>>(8-(posBit+1)) & 0x0001;
return valInt;
}
private static void setBit(byte[] data, int pos, int val) {
int posByte = pos/8;
int posBit = pos%8;
byte oldByte = data[posByte];
oldByte = (byte) (((0xFF7F>>posBit) & oldByte) & 0x00FF);
byte newByte = (byte) ((val<<(8-(posBit+1))) | oldByte);
data[posByte] = newByte;
}
private static byte[] readBytes(String in) throws Exception {
FileInputStream fis = new FileInputStream(in);
int numOfBytes = fis.available();
byte[] buffer = new byte[numOfBytes];
fis.read(buffer);
fis.close();
return buffer;
}
private static void writeBytes(byte[] data, String out)
throws Exception {
FileOutputStream fos = new FileOutputStream(out);
fos.write(data);
fos.close();
}
private static void printBytes(byte[] data, String name) {
System.out.println("");
System.out.println(name+":");
for (int i=0; i<data.length; i++) {
System.out.print(byteToBits(data[i])+" ");
}
System.out.println();
}
private static String byteToBits(byte b) {
StringBuffer buf = new StringBuffer();
for (int i=0; i<8; i++)
buf.append((int)(b>>(8-(i+1)) & 0x0001));
return buf.toString();
}
}
If you run this program with JDK 1.4.1 with test key and clear text block
mentioned in the previous chapter, you will get:
java -cp . CipherDES encrypt TestKey.des TestMsg.clr TestMsg.cph
Key block:
00010011 00110100 01010111 01111001 10011011 10111100 11011111 11110001
Input block:
00000001 00100011 01000101 01100111 10001001 10101011 11001101 11101111
Output block:
10000101 11101000 00010011 01010100 00001111 00001010 10110100 00000101
java -cp . CipherDES decrypt TestKey.des TestMsg.cph TestMsg.bck
Key block:
00010011 00110100 01010111 01111001 10011011 10111100 11011111 11110001
Input block:
10000101 11101000 00010011 01010100 00001111 00001010 10110100 00000101
Output block:
00000001 00100011 01000101 01100111 10001001 10101011 11001101 11101111
As you can see from the output, the program works perfectly.
(Continued on next part...)
Part:
1
2
3
4
|