In my next posts on java development I’m gonna share with you a series of encryption algorithms implemented in java(not quite fast but more clear and organized).

I’ll start with a good old one: DES algorithm.This is good for introduction, because it represent an old standard on which many new algorithms are built, and is quite easy to understand. It will naturally lead to another algorithm: Triple DES – as you’ll see later.

DES is a symmetric block cipher, operating on blocks of 64 bits of data and a key of 64 bits. Deciphering is done with the same key but in reverse order. Only 56 bits of the key are used actually in the process. Remaining 8 bits are used for parity check, therefore can be discarded.

Next is a brief description of the algorithm along with the code.

### Encryption algorithm

The overall structure of encryption steps are as follows:

- A block of 64 bits is permuted by an initial permutation called IP.
- Resulting 64 bits are divided in two halves of 32 bits, left and right.
- Right half goes through a function F(Feistel function)
- Left half is XOR-ed with output from F function above.
- Left and right are swapped(except last round).
- If last round, apply an inverse permutation IP-1 on both halves and that’s the output else, goto step 3.

Steps 3-5 constitute a round. DES has 16 identical rounds. Note the two halves are processed alternately. This structure represents what is called a Feistel network.

Feistel function F is represented by the following operations:

- Expansion – 32 bits to 48 bits based on an expansion table.
- Key mixing – round key combined with 48 bits from previous step by XOR operation.
- Substitution – previous result divided into 8x6bits blocks before processed by s-boxes(substitution boxes)
- Permutation based on a fixed permutation table.

I’ll show in code the above steps. For more details about the theory behind this consult the official document. I highly advise to read it along with my explanation.

### Function encrypt64Bloc

private static byte[] encrypt64Bloc(byte[] bloc,byte[][] subkeys, boolean isDecrypt) { byte[] tmp = new byte[bloc.length]; byte[] R = new byte[bloc.length / 2]; byte[] L = new byte[bloc.length / 2]; tmp = permutFunc(bloc, IP); L = extractBits(tmp, 0, IP.length/2); R = extractBits(tmp, IP.length/2, IP.length/2); for (int i = 0; i < 16; i++) { byte[] tmpR = R; if(isDecrypt) R = f_func(R, subkeys[15-i]); else R = f_func(R,subkeys[i]); R = xor_func(L, R); L = tmpR; } tmp = concatBits(R, IP.length/2, L, IP.length/2); tmp = permutFunc(tmp, invIP); return tmp; }

This is the main function. Is used for both encryption/decryption pointed out by the last param.

It requires a fixed length block of 64 bits of data and the subkeys from the key schedule.

You can see the overall structure: apply initial permutation, divide the block, run through 16 rounds with the corresponding operation, apply inverse permutation and return the result.

### Utility functions

- Function
**setBit**– given a vector of bytes, a position and a value(0 or 1) it sets the correpsonding bit in the vector to the given value. It calculates the byte position and bit position within that byte position which needs to be set.

private static void setBit(byte[] data, int pos, int val) { int posByte = pos / 8; int posBit = pos % 8; byte tmpB = data[posByte]; tmpB = (byte) (((0xFF7F >> posBit) & tmpB) & 0x00FF); byte newByte = (byte) ((val << (8 - (posBit + 1))) | tmpB); data[posByte] = newByte; }

- Function
**extractBit**– similar to setBit – extract the bit from the given position.

private static int extractBit(byte[] data, int pos) { int posByte = pos / 8; int posBit = pos % 8; byte tmpB = data[posByte]; int bit = tmpB >> (8 - (posBit + 1)) & 0x0001; return bit; }

- Function
**extractBits**– given a vector of bytes, extract a series of consecutive bits from a starting position and a given length. It uses the above helper functions

private static byte[] extractBits(byte[] input, int pos, int n) { int numOfBytes = (n - 1) / 8 + 1; byte[] out = new byte[numOfBytes]; for (int i = 0; i < n; i++) { int val = extractBit(input, pos + i); setBit(out, i, val); } return out; }

- Function
**rotLeft**– given an input vector of bytes rotates bits to the left by given number of positions. For flexibility, there’s a param len indicating how many bits from the input vector to be rotated, allowing you to rotate just fragments of the input vector.

private static byte[] rotLeft(byte[] input, int len, int pas) { int nrBytes = (len - 1) / 8 + 1; byte[] out = new byte[nrBytes]; for (int i = 0; i < len; i++) { int val = extractBit(input, (i + pas) % len); setBit(out, i, val); } return out; }

- Function
**xor_func**– as simple as it sounds – apply xor function on two vector of bytes.

private static byte[] xor_func(byte[] a, byte[] b) { byte[] out = new byte[a.length]; for (int i = 0; i < a.length; i++) { out[i] = (byte) (a[i] ^ b[i]); } return out; }

- Function
**separateBytes**– this will help separating block of bytes in chunks of variable number of bits. Given a vector of bytes it will extract groups of bits of the given length, putting them in separate bytes.

private static byte[] separateBytes(byte[] in, int len) { int numOfBytes = (8 * in.length - 1) / len + 1; byte[] out = new byte[numOfBytes]; for (int i = 0; i < numOfBytes; i++) { for (int j = 0; j < len; j++) { int val = extractBit(in, len * i + j); setBit(out, 8 * i + j, val); } } return out; }

- Function
**concatBits**– concatenate bits from 2 input vector of bytes, given, for each vector, how many bits to take from them.

private static byte[] concatBits(byte[] a, int aLen, byte[] b, int bLen) { int numOfBytes = (aLen + bLen - 1) / 8 + 1; byte[] out = new byte[numOfBytes]; int j = 0; for (int i = 0; i < aLen; i++) { int val = extractBit(a, i); setBit(out, j, val); j++; } for (int i = 0; i < bLen; i++) { int val = extractBit(b, i); setBit(out, j, val); j++; } return out; }

### DES Specific functions

- Function
**permutFunc**– is a generalized function for applying a permutation on a vector of bytes. It requires also as param the table of permutation. Permutations are performed bitwise. Bits are permuted based on the elements of the table. For example if first element of table is 57 then bit 57 will be bit 1 in the permuted block of bytes. Expansion permutation is similar except in its table, some values repeat, that’s why it will result a larger number of bits.

private static byte[] permutFunc(byte[] input, int[] table) { int nrBytes = (table.length - 1) / 8 + 1; byte[] out = new byte[nrBytes]; for (int i = 0; i < table.length; i++) { int val = extractBit(input, table[i] - 1); setBit(out, i, val); } return out; }

- Function
**f_func**– is the Feistel function. It consist of other function calls, resembling steps described earlier.

private static byte[] f_func(byte[] R, byte[] K) { byte[] tmp; tmp = permutFunc(R, expandTbl); tmp = xor_func(tmp, K); tmp = s_func(tmp); tmp = permutFunc(tmp, P); return tmp; }

- Function
**s_func**– apply the 8 s-boxes to the 48bits of data resulting 32 bits of output. The 48 bits are divided in groups of 6 bits. First and last bit of each group will indicate a row in s-box.Middle 4 will indicate a column. corresponding value of 4 bits from the s-box will substitute the input of 6 bits.

private static byte[] s_func(byte[] in) { in = separateBytes(in, 6); byte[] out = new byte[in.length / 2]; int halfByte = 0; for (int b = 0; b < in.length; b++) { byte valByte = in[b]; int r = 2 * (valByte >> 7 & 0x0001) + (valByte >> 2 & 0x0001); int c = valByte >> 3 & 0x000F; int val = sboxes[b][r][c]; if (b % 2 == 0) halfByte = val; else out[b / 2] = (byte) (16 * halfByte + val); } return out; }

This are all the functions necessary to encrypt a single block of 64 bits. For extending this to variable length of clear text, there’s another function in the code called encrypt which is actually public, representing the interface with the user. You can call this with any data. It will add padding to data, for making it a multiple of 64(8 bytes).Padding is in the format: first bit ‘1’, rest of them ‘0’. This way, padding can be easily removed from the decrypted cipher text.

For more details about this function and decrypt function and also tables of permutation values, check out the entire source code to see how it comes together.

### Key Schedule

- 64 bits goes through a permutation called PC-1(permuted choice) resulting 56 bits.
- 56 bits are divided into two halves
- Each half will be rotated left by 1 or 2 bits depending on the round
- Both sides go through permutet choice 2 (PC-2) which selects 24 bits from left and right resulting a 48 bit round key.

Following is the method for generating subkeys

private static byte[][] generateSubKeys(byte[] key) { byte[][] tmp = new byte[16][]; byte[] tmpK = permutFunc(key, PC1); byte[] C = extractBits(tmpK, 0, PC1.length/2); byte[] D = extractBits(tmpK, PC1.length/2, PC1.length/2); for (int i = 0; i < 16; i++) { C = rotLeft(C, 28, keyShift[i]); D = rotLeft(D, 28, keyShift[i]); byte[] cd = concatBits(C, 28, D, 28); tmp[i] = permutFunc(cd, PC2); } return tmp; }

Source code contains also a variation of Triple DES(see mode of operation for cryptographic algorithms). 3DES is a much stronger algorithm. Uses three 64 bit keys and blocks are encrypted with one key, then decrypted with second key, and again encrypted with the last key. Decryption process is similar but in reverse order.

DES is no more secure, mainly because its short key length, being breakable by brute force attack in a convenient time.

Thank for Solution! But I need main for DES.java only.

You’re welcome!

You can find the main class in my AES post as an Eclipse project.

It has test cases for DES, if that’s what you need.

Best regards!

Thank you very much for sharing knowledge for me.

Hello!

I have problem with Encryption from C, but I want use java for Decrypt.

we have 1234 after Encrypt B43B5639030CFE82.

Please Tell me the algorithms for solution this problem. I try to used Algorithms DES by java form you but after Decrypt not right.

Thank you!

Hello!

I would like to help, but I’m not clear with the problem you’ve encountered.

As I understand, you’ve encrypted with C and decrypt with my java class. Is that right?

Maybe, you could share with me your C algorithm, and exact steps you’ve taken as I’m not able to give you an answer without testing it myself.

I’m not assuming my code is error free, because it was made as an exemplification of the algorithm.

Another suggestion, if you’re trying to create a more optimal program, would be to use cryptographic libraries, such as those in the package javax.crypto…perhaps there is a DES algorithm too in there.

Hello!

Now, I want to know Hibernet technology in java. Could you give me Ebook for learn Hibernet ? because my teach give me an assignment that use Hibernet and java language. if you can please help me!

My teacher toll me Oracle Database is very important, but I don’t know about it. Please me about Oracle Database.

Thank you!

Hello!

I have some problem give you help me. Please give me, 1DES by Java Example.

I can’t solve my problem. Please help me.

If you can pleas give me 2DES, 3DES Algorithms, and give the example of all.

Thank you.

Hello!

Sry, I haven’t worked with Hibernet. I can’t ofer you nothing more than what you can find out with google.

Personally, I prefer MySQL for database as I come from a php enviromnent. You can connect to it with mysql java connector.

This is all I can help you with. Maybe, I will post on this blog stuff about this subject when I’ll have some time, as I’m interested too in learning new tehnologies.

Best regards!

Hello!

I have some problem give you help me. Please give me, 1DES by Java Example.

I can’t solve my problem. Please help me.

If you can pleas give me 2DES, 3DES Algorithms, and give the example of all.

Thank you.

hi can i get DES java script

in my project i want to encrypt in JavaScript and Decryption in Java

plss provide me

thanks advance

Hello!

I’m sorry but I don’t have a javascript algorithm, neither do I have time to implement it.

You should try to search for it. Maybe it’s already done, or you could try and rewrite my algorithm in js.

Best regards!

i need DES algorithm(encryption and decryption ) saparetlly code in java

all you need is the DES.java file. There’s the encryption and decryption functions. You should try split them in two files.

Best regards!

hi i want using DES to encrypt and decrypt image but i dont have the algorithm in java with netbeans can you help me

Hi,

I don’t use netbeans but as far as it’s java, you could download my source code an put the files in your netbeans project.

Then, read the image as a stream of bytes and send it to DES function.

Hope it helps

Best regards!

Hai , Do u know what type of encryption algorithm using in smartcard chip and pin.what are the datas inside the chip.

Hi,

No, sry, I’m not aware of such information.

Hai,

Am interested to do my research in Computing and security . But i don know how to write the proposal for this . Am doing this research alone for past 2 years . And i found of useful

information for the UK top bankers but how to outcome this.

Very helpful! Thank you very much for posting such valuable articles! Special thanks for posting simple and working code example.

Hello!

I had to make an implementation of the Ladder-DES for college, and your DES implementation helped me a lot. Thank you very much!

Greetings from Brazil!

hi

why do subtract by 1 and divide by 8+1 instead of 8? For example :

int nrBytes = (len – 1) / 8 + 1;

many thanks

Hi,

As I remember, I used that in case len is a number of bits under 8.

if let’s say I want 4 bits from something I still need a byte to store them as it is the smallest unit.

so (4-1)/8 + 1 = 1

and I found this it extends to all len sizes as it gives the correct number of bytes to use.

maybe you can find a more elegant way :P. Hope it helps.

thanks!! :) so i made my own permute methods, how can I test that it’s actually permuting properly? are there any java methods for this? to show sequences of bits?

you could extract bits from a byte to dispay them..or display bytes in hex and convert etc. Don’t know of a direct method but it could be. or you can test it in algorithm itself..see if it encrypt/decrypt properly

Thanks for your reply, one last question: when you make the subkeys, and divide the 58 bit key to two halfs C and D, is C the first 28 bit and D the last 28 bit?

thanks!! so i made my own permute method, how can I test that it’s actually permuting properly? are there any java methods for this? to show sequences of bits?

Dear N3vrax,

I’ve recently been looking at DES, and stumbled across this blog post – needless to say, it is very helpful.

One thing confused me though – in your setBit method, you have the line:

tmpB = (byte) (((0xFF7F >> posBit) & tmpB) & 0x00FF);

Now, FF7F in decimal/binary is 65407/1111111101111111 respectively – I am wondering if you could explain why you chose this value, and 00FF, to me? Your help would be greatly appreciated.

Hi,

– after getting the byte position and bit position affected we store that byte into a temporary byte(tmpB)

– first thing to do is set the bit we want to change to 0.

– the shift operator in java, if I’m correct it is sign based

– 7F part from the constant is 0111.1111 a byte with position at index 0 having value 0.(btw, this is how I consider bit position – from left to right – very important to choose how you want to consider positions and stick to it in all your functions)

– now if we shift 7F we’ll get 0 in all positions above the one we want which is not desirable. so I extended the constant to 2 bytes long with 1 at the higher positions. Now if we shift we’ll get 1 in front of the 0 bit.

– after the shift bitwise AND sets the bit in tmpB to 0 leaving all others untouched.

– 0x00FF – I mask all higher bits which comes from the extended constant – that’s the window we are interested in – 1 byte as an output.

I’ll give an example to make myself clear:

data: 00100111.00100011.01110011 – 3 bytes

pos: 12

val: 1

posByte = 1 => tmpB: 00100011

posBit = 4 so we want to change the bit between the dots 0010.0.011

0xFF7F: 11111111.01111111

>> 4 11111111.11110111 &

tmpB: ????????.00100011

=> ????????.00100011 &

0x00FF: 00000000.11111111

=> 00000000.00100011 casted to byte so tmpB final form is 00100011

having this we are sure the target bit is always 0. Next we move val (0 or 1) to the desired bit position and apply bitwise OR

Hope it’s clear.

Many thanks for the speedy reply! I wasn’t sure if you’d still be monitoring posts from a year and a half ago. It’s all clear now, you’re a star.

Dear N3vrax,

It’s me again. I noticed that your Java implementation is copyrighted – may I have your permission to reference your work in a report for my degree? Many thanks.

Hi there,

Yes of course you can, I don’t remember to put a copyright there :P. Maybe I was joking. Anyways you can use it, at least mentioning this blog, if possible.

Thanks and Good Luck

Hello, after reading this remarkable piece

of writing i am too delighted to share my knowledge here with mates.

I wan’t to download java ….any help

does this code work ?

This is just a separate class implementing DES. You must put it in a project to work.

If you find it dificult to run, go to my AES Java implementation post and download the entire Eclipse project. That is a working example containing all algorithm presented.

ok .. thank you … where can i find your AES implementation

and when i run your code need tsd.crypto how can import it do you hava the code? plz hlp

sorry i find the AES on your blog but i need to know how i import this pckge tsd.crypto

if I may add, I still don’t understand the reason for you to put 0x80 at the beginning of the padding. could you please explain it to me?

thanks a lot :)

Hi,

if I recall, the padding is in the form 10000…

so when I try to delete the padding I know I have to start from end of array until value is different than 0, and I trim that.

Note that input data is still padded with data even if not necessary, so I know padding is present in every case. This way, I’m not risking to trim useful data.

Thanks for all your work. It was very helpfull.

Hey, thanks for posting this; I wanted to drop you a line to let you know that I’m cribbing EXTREMELY heavily off of your work here for a quick java implementation of DES in a crypto challenge I’m helping put together for some coworkers of mine. I’m absolutely making a note of where I got the code and including a link to your blog in the comments, but I wanted to touch base with you and let you know personally what the situation was in case you ever came across the challenge in the wild and thought, scratching your head, that this DES stuff looks awfully familiar. If you have any questions about what I’m doing or why, please don’t hesitate to email me!

Hi, glad it helps. Feel free to use the code in your projects :).

Thanks!

Hi, I’m trying to go about implementing only one round of this, can I have some help around that? Thanks.

hello,could you plz help me i have a des project and i need to implement the different modes of crypting like ECB,CBC,… what would i do ? if you plz reply me asap.

Thanks in advance !!!

here’s a good article

http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation

as far as my implementation, I think it is ECB

you shouldn’t have difficulties changing it if you understand the algorithm.

This is all I can help you with.

Good luck!

Hello n3vrax

How are you? I first want to thank you for helping people around the world. I am seeking guidance on how to approach my homework. here it is below:

Write a program that implements the full DES. Use the S-boxes that are specified for the DES standard. Make sure you implement all of the key generation steps. For the encryption key, your program should prompt the user for a keyboard entry that consists of at least 8 printable ASCII characters. (You may choose to either use the first seven or the last seven bits of each character byte for the 56-bit key you need for DES.)

I see that you posted source code, can i use it? if so where to put the scanner method to ask user imput and such.

THank!!!

Hi,

You may use this code freely. As for the input, you should put this outside this class. Make a test case for it, from which you call class methods. Check out a complete eclipse project with test cases in my AES post, which includes all algorithms

THank you, should i put the imput code in the main class and you have listed the AES whats that?

yes, in your main class. I have another post on this blog about AES algorithm where you can find an eclipse project example with a main class for testing.

With in the AES project, you have 8 classes. Does all extends each other ? or do i simply need the Main and DES class to accomplish my goal? which is :

To Write a program that implements the full DES. Use the S-boxes that are specified for the DES standard. Make sure you implement all of the key generation steps. For the encryption key, your program should prompt the user for a keyboard entry that consists of at least 8 printable ASCII characters. (You may choose to either use the first seven or the last seven bits of each character byte for the 56-bit key you need for DES.).

Thank you

i am having some problem when i try to encrypt a large file with ur des algm it is working fine with text files but not working with any other formats i think there is some problem with the decryption section could u help me out on that…

didn’t try it with binary data, I made this just for showing how the algorithm works at its basics. Sry I can’t help, I’m not having time for this

http://sagarlone.weebly.com/network-security-algorithm-implementation.html

some algorithm implementation

Hey i got ur eclipse code for DES and AES and i think they are in ECB mode. Can you upload code for Other modes i.e., CBC,CTR and OFB??

Hi,

I don’t have those modes implemented, but it should be fairly easy to modify my version following the docs

ok.. thanks a lot :)

Hey there!

First I would like to say thank you for your java implementation code for DES which helped me a lot, it’s just I have an assignment for homework to do using DES and it goes like this:

1. What is the output of the first round in DES when you use plaintext and key consisted only of 0? (000..0)

2. What is the output of the first round in DES when you use plaintext and key consisted only of1? (111..1)

3. Prove with an example: S1(x1) + S1(x2) ≠ S1(x1 + x2)

Whenever I run your program and change the key in “111111” or “00000” i get many errors, exceptions etc. so I can’t answer my questions.

If possible, please rewrite these for me in the main, so I can test the program in the first round (how?) – it means a lot to me.

I appreciate, thanks.

I’m sorry I can’t help

This programs were created as a project for school, and I really don’t have time to dig into this right now

Hi n3vrax, thank you for your detail about your tutorial, but I have one question for you about implementing 3DES with your algorithm, whether we use two keys input or use only one? Thank you for your reply and sorry about my English.

Hi n3vrax, thank you for your detail about your tutorial, but I have one question for you about implementing 3DES with your algorithm, whether we use two keys input or use only one? Thank you for your reply and sorry about my English

please help i want des decrypt code with 16 steps output

Hello, I am trying to make a class named schedule to generate the subkeys from the main key but it has no effect on the byte[][]k which represents the subkeys in ur implementationn and it cause null exception… And why if we release static characteristic from all methods and values, the encryption and description are not done in a good manner. Thanks

This is Great

Thank you very much to post this algorithm. I can encrypt and decrypt image with this. Another DES algorithm that I found, is not support for encryp or decrypt an image.

Thank you for this..