• Save
Advanced Encryption Standard (AES) Implementaion using Java
Upcoming SlideShare
Loading in...5
×
 

Advanced Encryption Standard (AES) Implementaion using Java

on

  • 4,732 views

 

Statistics

Views

Total Views
4,732
Views on SlideShare
4,732
Embed Views
0

Actions

Likes
16
Downloads
2
Comments
2

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Advanced Encryption Standard (AES) Implementaion using Java Advanced Encryption Standard (AES) Implementaion using Java Document Transcript

  • Department of Computer Science and Engineering R. V. College of Engineering , Bangaluru – 560 059 (Affiliated to VTU, Karnataka, Accredited by AICTE, New Delhi) 2012-13 A Project report on “IMPLEMENTATION OF AES ALGORITHM” Submitted in partial fulfillment of the requirements for the award of the degree of Bachelor of Engineering in Computer Science & Engineering By SUNIL KUMAR R SHREEKANT 1RV11CS420 1RV10CS417 Under the guidance of Mrs. Jyothi Shetty Assistant Professor Department of CSE Mrs. D.Pratiba Assistant Professor Department of CSE Mrs. Prapulla S B Assistant Professor Department of CSE Carried out at Department Of Computer Science & Engineering R. V. College of Engineering
  • R. V. COLLEGE OF ENGINEERING (Autonomous Institution under VTU), Bangalore – 560 059 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, CERTIFICATE This is to certify that SUNIL KUMAR R and SHREEKANT has satisfactorily completed the project on “IMPLEMENTATION OF AES ALGORITHM” in the COMPUTER NETWORKS course in the laboratory of this college in the year 2012-13. Name of the Candidates: Sunil Kumar R Shreekant Signature of the HOD Dept. of CSE (1RV11CS420) (1RV11CS417) Signature of the Staff in-charge of the batch 1) 2) 3) Signature of the external examiner 1) 2)
  • R.VCOLLEGE OF ENGINEERING, BANGALORE - 560059 (Autonomous Institution Affiliated to VTU, Belgaum) DEPARTMENT OF COMPUTER SCIENCE DECLARATION We , Sunil Kumar R (1RV11CS420) and Shreekant (1RV11CS417), the students of 6th semester B.E., Computer Science, hereby declare that the project titled “IMPLEMENTATION OF AES ALGORITHM ” has been carried out by us and submitted in partial fulfillment for the award of degree of Bachelor of Engineering in Computer science. We do declare that this work is not carried out by any other students for the award of degree in any other branch. Place: Bangalore Date: Signature 1.SUNILKUMAR R 2.SHREEKANT
  • ACKNOWLEDGEMENT Any achievement, be it scholastic or otherwise does not depend solely on the individual efforts but on the guidance, encouragement and cooperation of intellectuals, elders and friends. A number of personalities, in their own capacities have helped me in carrying out this project work. We would like to take this opportunity to thank them all. First and foremost we would like to thank Dr. B. S. Satyanarayana, Principal, R.V.C.E, Benguluru, for his moral support towards completing our project work. We would like to thank Dr. N. K. Srinath, Head of Department, Computer Science & Engineering, R.V.C.E, Benguluru, for his valuable suggestions and expert advice. We deeply express our sincere gratitude to our faculty in-charge for their able guidance, regular source of encouragement and assistance throughout this project. We thank all the Faculty members and Technical / Administrative Staff of Department of Computer Science & Engineering for their constant support and encouragement. Last, but not the least, we would like to thank our peers and friends who provided us with valuable suggestions to improve our project I
  • ABSTRACT In today’s world most of the communication is done using electronic media. Data Security plays a vital role in such communication. Hence, there is a need to protect data from malicious attacks. This can be achieved by Cryptography. The earlier encryption algorithm is Data Encryption Standard (DES) which has several loopholes such as small key size and sensible to brute force attack etc. and it can’t provide high level, efficient and exportable security. These loopholes overcome by a new algorithm called as Advanced Encryption Standard (AES). In this project work, the plain text of 128 bits is given as input to encryption block in which encryption of data is made and the cipher text of 128 bits is throughout as output. The key length of 128bits, 192bits or 256bits is used in process of encryption. The AES algorithm is a block cipher that uses the same binary key for both encryption and decryption of data blocks. Hence it is called a symmetric key cryptography. The rounds in decryption are exact inverse of encryption. There are four rounds in encryptions viz. SubBytes, ShiftRows, MixColumns and AddRoundKey. Similarly for Decryption we have InvSubBytes, InvShiftRows, InvMixColumns and InvAddRoundKey. The number of times operation performed is depend on key length i.e. for 128bis we have 10 rounds. Since operations in AES are difficulty, there exists no attack better than key exhaustion to read an encrypted message. Ultimately, anyone can use AES encryption methods, and it is free for public or private, commercial or non-commercial use. The simplest version encrypts and decrypts each 128-bit block individually. It gives better security than DES versions and also better throughput. II
  • TABLE OF CONTENTS Chapter Pages ACKNOWLEDGMENT ABSTRACT II TABLE OF CONTENTS III List of Figures 1 I V 1-3 1.1 Definitions 1 1.2 Purpose 2 1.3 Motivation 2 1.4 Organization of the Report 2 Introduction 3 Software Requirement Specification 4-5 2.1 Hardware Requirements 4 2.2 Software Requirements 4 2.3 Functional Requirements 4 2.3.1 Input specification 2.3.2 Output specification 3 4 5 High level Design 3.1 Advanced Encryption Standard 6-9 6 3.1.1 Overview 6 3.1.2 Overall process of AES algorithm 6 3.2 Flow chart 4 Detail Design 4.1 AES Encryption operation 9 10-20 10 III
  • 4.1.1 SubBytes 11 4.1.2 ShiftRows 13 4.1.3 MixColumns 13 4.1.4 AddRoundKey 15 4.2 AES Decryption operation 15 4.2.1 InvSubBytes 16 4.2.2 InvShiftRows 17 4.2.3 InvAddRoundKey 18 4.2.4 InvMixColumns 18 4.3 Key Expansion 19 5 Implementation details 21-21 6 Conclusion 22-22 6.1 Limitations 22 6.2 Conclusions 22 References 23 APPENDIX -A Source Code 24-48 APPENDIX -B Screenshots 49-50 IV
  • List of Figures Figure (1) AES Structure 08 Figure (2) AES Encryption Flowchart 09 Figure (3) S-Box Values 12 Figure (4) SubBytes operation 12 Figure (5) ShiftRows operation 13 Figure (6) MixColumn operation 14 Figure (7) InvSbox values 17 V
  • AES Algorithm 1. Introduction In today’s world most of the communication is done using electronic media. Data Security plays a vital role in such communication. Hence, there is a need to protect data from malicious attacks. This can be achieved by Cryptography. The earlier encryption algorithm is Data Encryption Standard (DES) which has several loopholes such as small key size and sensible to brute force attack etc. and it can’t provide high level, efficient and exportable security. These loopholes overcome by a new algorithm called as Advanced Encryption Standard (AES). In this project work, the plain text of 128 bits is given as input to encryption block in which encryption of data is made and the cipher text of 128 bits is throughout as output. The key length of 128bits, 192bits or 256bits is used in process of encryption. The AES algorithm is a block cipher that uses the same binary key for both encryption and decryption of data blocks. 1.1 Definitions  Cryptography Cryptography is the science of secret codes, enabling the confidentiality of communication through an insecure channel. It protects against unauthorized parties by preventing unauthorized alteration of use. Generally speaking, it uses a cryptographic system to transform a plaintext into a cipher text, using most of the time a key. It has different Encryption and Decryption algorithms to do so.  Cipher Text This is the scrambled message produced as output from Encryption algorithm. It depends on the plaintext and the secret key. For a given message, two different keys will produce two different cipher texts.  Encryption Encryption is the process of converting data, in plain text format into a meaningless cipher text by means of a suitable algorithm. The algorithm takes secret key and plain text as input and produces cipher text. Dept. of CSE, RVCE 1
  • AES Algorithm  Decryption Decryption is converting the meaningless cipher text into the original information using decryption algorithms. The decryption algorithm is inverse of encryption algorithm. This takes key and cipher text as input and produces original plain text.  Symmetric key cryptography Symmetric cryptography uses the same secret (private) key to encrypt and decrypt its data. It requires that the secret key be known by the party encrypting the data and the party decrypting the data.  Asymmetric key cryptography Asymmetric uses both a public and private key. This allows for distribution of your public key to anyone with which they can encrypt the data they want to send securely and then it can only be decoded by the person having the private key. 1.2 Purpose In today’s world most of the communication is done using electronic media. Data Security plays a vital role in such communication. Hence, there is a need to protect data from malicious attacks. This can be achieved by Cryptography. The earlier encryption algorithm is Data Encryption Standard (DES) which has several loopholes such as small key size and sensible to brute force attack etc. These loopholes overcome by a new algorithm called as Advanced Encryption Standard Algorithm. 1.3 Motivation The Advanced Encryption Standard, in the following referenced as AES, is the winner of the contest, held in 1997 by the US Government, after the Data Encryption Standard (DES) was found too weak. Fifteen candidates were accepted in 1998 and based on public comments the pool was reduced to five finalists in 1999. In October 2000, one of these five algorithms was selected as the forthcoming standard: a slightly modified version of the Rijndael. Dept. of CSE, RVCE 2
  • AES Algorithm The Rijndael, whose name is based on the names of its two Belgian inventors, Joan Daemen and Vincent Rijmen, is a Block cipher, which means that it works on fixed-length group of bits, which are called Blocks. It takes an input block of a certain size, usually 128, and produces a corresponding output block of the same size. The transformation requires a second input, which is the secret key. It is important to know that the secret key can be of any size (depending on the cipher used) and that AES uses three different key sizes: 128, 192 and 256 bits. 1.4 Organization of the Report The 1st Chapter gives the basic definitions of terms that are used in this report and purpose of project and also gives the motivation behind implementing this project. The 2nd Chapter gives the details of requirnments for implementing the project. It gives Hardware, Software and user requirenments. The 3rd Chapter gives the overview and process structure of this project. It also gives the flowcharts. The 4th Chapter gives the details of each modules used in this project. The 5th Chapter gives some implementation details i.e. how we implemented it, and which method perform what operation etc. The 6th Chapter gives conclusion, limitations and further enhancement to the project. References section provide source detail where we get information. It gives name books, authors, year of published etc. and also some websites helped for implementation. Appendix A contain Source code and Appendix B Contain Snapshots of the project. Dept. of CSE, RVCE 3
  • AES Algorithm 2. System Requirement Specification 2.1 Hardware Requirement  2 computers i.e. one for Client and another for Server  Internet connection i.e. for IP address  32B RAM or above  X86 or above processor  2MB Secondary memory or above 2.2 Software Requirement  Operating System  LINUX  Windows  Language used  Java  Editor  MyEclipse  VI  Other Library  Sun.misc.BASE64Encoder  Sun.misc.BASE64Decoder 2.3 Functional Requirement 2.3.1 Input Specification  An input file which is of .txt format and should contain some data.  Project file should contain clenc.txt at client side i.e. used for intermediate storage to store encrypted file.  IP Address of second part should know.  Secret key used for encryption should of 128bits, 192bits or 256bits. Dept. of CSE, RVCE 4
  • AES Algorithm 2.3.2 Output Specification  At server side, second party should know secret key that used for encryption.  After providing secret key as input, it displays the original Plain Text. Dept. of CSE, RVCE 5
  • AES Algorithm 3. High level Design 3.1 Advanced Encryption Standard 3.1.1 Overview Advanced Encryption Standard (AES) is a Symmetric key cryptography and it is an iterated block cipher with a fixed block size of 128 bit and a variable key length i.e. it may be 128, 192 or 256 bits. The different transformations operate on the intermediate results, called state. The state is a rectangular array of bytes and since the block size is 128 bits, which is 16 bytes, the rectangular array is of dimensions 4x4. (In the Rijndael version with variable block size, the row size is fixed to four and the number of columns varies. The number of columns is the block size divided by 32 and denoted Nb). The cipher key is similarly pictured as a rectangular array with four rows. The number of columns of the cipher key, denoted Nk, is equal to the key length divided by 32. AES uses a variable number of rounds, which are fixed: A key of size 128 has 10 rounds. A key of size 192 has 12 rounds. A key of size 256 has 14 rounds. An algorithm starts with a random number, in which the key and data encrypted with it are scrambled though four mathematical operation processes. The key that is used to encrypt the number must also be used to decrypt it. For encryption, each rounds has four operations SubBytes, ShiftRows, MixColumns, and AddRoundKey respectively, and for decryption it use inverse of these function. All these functions are described in chapter 4. Below figure (1) shows the structure of AES algorithm. 3.1.2 Overall process AES algorithm 1. AES does not use a Feistel structure but processes the entire data block in parallel during each round using substitutions and permutation. 2. The key that is provided as input is expanded into an array of forty-four 32-bit words. Four distinct words (128 bits) serve as a round key for each round. 3. Four different stages are used, one of permutation and three of substitution:  SubstituteBytes: Uses a table, referred to as an S-box, to perform a byte-by byte substitution of the block. Dept. of CSE, RVCE 6
  • AES Algorithm  ShiftRows: A simple permutation that is performed row by row.  MixColumns: A substitution that alters each byte in a column as a function of all of the bytes in the column.  AddRoundKey: A simple bitwise XOR of the current block with a portion of the expanded key. 4. The structure is quite simple. For both encryption and decryption, the cipher begins with an Add Round Key stage, followed by nine rounds that each includes all four stages, followed by a tenth round of three stages. 5. Only the Add Round Key stage makes use of the key. For this reason, the cipher begins and ends with an Add Round Key stage. Any other stage, applied at the beginning or end, is reversible without knowledge of the key and so would add no security. 6. The Add Round Key stage by itself would not be formidable. The other three stages together scramble the bits, but by themselves, they would provide no security because they do not use the key. We can view the cipher as alternating operations of XOR encryption (Add Round Key) of a block, followed by scrambling of the block (the other three stages), and followed by XOR encryption, and so on. This scheme is both efficient and highly secure. 7. Each stage is easily reversible. For the Substitute Byte, Shift Row, and Mix Columns stages, an inverse function is used in the decryption algorithm. For the Add Round Key stage, the inverse is achieved by XORing the same round key to the block, using the result that A B B = A. 8. As with most block ciphers, the decryption algorithm makes use of the expanded key in reverse order. However, the decryption algorithm is not identical to the encryption algorithm. This is a consequence of the particular structure of AES. 9. Once it is established that all four stages are reversible, it is easy to verify that decryption does recover the plaintext. Dept. of CSE, RVCE 7
  • AES Algorithm 10. The final round of both encryption and decryption consists of only three stages. Again, this is a consequence of the particular structure of AES and is required to make the cipher reversible. Figure(1) shows AES Structure Dept. of CSE, RVCE 8
  • AES Algorithm 3.2 Flow Chart Figure (2) shows AES Encryption Dept. of CSE, RVCE 9
  • AES Algorithm 4. Detailed Design 4.1 AES Encryption Operation Here is the AES algorithm is outline form, using Java syntax for the pseudocode, and much of the AES standard notation: Constants: int Nb = 4; // but it might change someday int Nr = 10, 12, or 14; // rounds, for Nk = 4, 6, or 8 Inputs: array in of 4*Nb bytes // input plaintext array out of 4*Nb bytes // output cipher text array w of 4*Nb*(Nr+1) bytes // expanded key Internal work array: state, 2-dim array of 4*Nb bytes, 4 rows and Nb cols Algorithm: void Cipher (byte[] in, byte[] out, byte[] w) { byte [][] state = new byte [4][Nb]; state = in; // actual component-wise copy AddRoundKey (state, w, 0, Nb - 1); // see Section 4 below for (int round = 1; round < Nr; round++){ SubBytes (state); // see Section 3 below ShiftRows (state); // see Section 5 below MixColumns (state); // see Section 5 below AddRoundKey (state, w, Round *Nb, (round+1)*Nb - 1); // Section 4 } SubBytes (state); // see Section 3 below ShiftRows (state); // see Section 5 below AddRoundKey (state, w, Nr*Nb, (Nr+1)*Nb - 1); // Section 4 out = state; // component-wise copy } There are four operations in AES Encryption as used in above snippet. They are, 1) SubBytes 2) ShiftRows Dept. of CSE, RVCE 10
  • AES Algorithm 3) MixColumns 4) AddRoundKey 4.1.1 SubBytes Many different block ciphers use a special substitution called an “S-box”. The AES also has these S-boxes, which it terms the “SubBytes Transformation”. S-boxes provide an invertible (reversible) transformation of segments of plaintext during encryption, with the reverse during decryption. With the AES it is a single simple function applied over and over again to each byte during stages of the encryption, returning a byte. Each of the 256 possible byte values is transformed to another byte value with the SubBytes transformation, which is a full permutation, meaning that every element gets changed, and all 256 possible elements are represented as the result of a change, so that no two different bytes are changed to the same byte. The SubBytes transformation changes a single entry as follows (here bi stands for the ith bit of a byte value b). byte SubBytesEntry (byte b) { byte c = 0x63; if (b != 0) } // leave 0 unchanged {timesbf b = multiplicativeInverse (b); for (i = 0 ; I < 8 ; i++) b[i] = b[i] ˆ b[(i+4)%8] ˆ b[(i+5)%8] ˆ b[(i+6)%8] ˆ b[(i+7)%8] ˆ c[i]; return b; } The Java pseudo-code for this part is now very simple, using the Sbox array defined above: void SubBytes(byte[][] state) { for (int row = 0; row < 4; row++) for (int col = 0; col < Nb; col++) state[row][col] = Sbox[state[row][col]]; } Dept. of CSE, RVCE 11
  • AES Algorithm Below figure(3) Shows the S-Box values and Figure(4) Shows SubBytes operation. Figure (3) Shows S-Box Values Figure (4) Shows SubBytes operation 4.1.2 ShiftRows The action of shifting rows is particularly simple, just performing left circular shifts of rows 1, 2, and 3, by amounts of 1, 2, and 3 bytes. Row 0 is not changed. The actual Java code below does this. void ShiftRows(byte[][] state) { byte[] t = new byte[4]; Dept. of CSE, RVCE 12
  • AES Algorithm for (int r = 1; r < 4; r++) { for (int c = 0; c < Nb; c++) t[c] = state[r][(c + r)%Nb]; for (int c = 0; c < Nb; c++) state[r][c] = t[c]; } } Below figure(5) shows ShiftRows operation Figure (5) Shows ShiftRow Operation 4.1.3 MixColumns The action of mixing columns works on the columns of the state array, but it is much more complicated that the shift columns action. As described in the AES specification, it treats each column as a four-term polynomial with coefficients in the field GF(28). All this is similar to the description of the field itself, except with an extra layer of complexity. These polynomials are added and multiplied just using the operations of the field GF(28) on the coefficients, except that the result of a multiplication, which is a polynomial of degree up to 6, must be reduced by dividing by the polynomial x4+1 and taking the remainder. The columns are each multiplied by the fixed polynomial: A(x) = (03) x3 + (01)x2 + (01)x + (02) where (03) stands for the field element 0x03. This sounds horrible, but mathematical manipulations can reduce everything to the following simple algorithm, where multiplication in the field is represented below by #. The principle change needed to convert this to actual Java is Dept. of CSE, RVCE 13
  • AES Algorithm to replace # with a call to FFMul(). (Gladman gives a shorter but more obscure version of this code.) Below figure(6) shows the MixColumn operation Figure(6) Shows MixColumn operation void MixColumns(byte[][] s) { byte[] sp = new byte[4]; for (int c = 0; c < 4; c++) { sp[0] = (0x02 # s[0][c]) ˆ (0x03 # s[1][c]) ˆ s[2][c] ˆ s[3][c]; sp[1] = s[0][c] ˆ (0x02 # s[1][c]) ˆ (0x03 # s[2][c]) ˆ s[3][c]; sp[2] = s[0][c] ˆ s[1][c] ˆ (0x02 # s[2][c]) ˆ (0x03 # s[3][c]); sp[3] = (0x03 # s[0][c]) ˆ s[1][c] ˆ s[2][c] ˆ (0x02 # s[3][c]); for (int i = 0; i < 4; i++) s[i][c] = sp[i]; } } 4.1.4 AddRoundKey As described before, portions of the expanded key w are exclusive-ored onto the state matrix Nr+1 times (once for each round plus one more time). There are 4*Nb bytes of state, and since each byte of the expanded key is used exactly once, the expanded key size of 4*Nb*(Nr+1) bytes is just right. The expanded key is used, byte Dept. of CSE, RVCE 14
  • AES Algorithm by byte, from lowest to highest index, so there is no need to count the bytes as they are used from w, but just use them up and move on, as the following near-Java code shows. This code assumes the key has already been expanded into the array w, and it assumes a global counter wCount initialized to 0. The function AddRoundKey uses up 4*Nb = 16 bytes of expanded key every time it is called. void AddRoundKey(byte[][] state) { for (int c = 0; c < Nb; c++) for (int r = 0; r < 4; r++) state[r][c] = state[r][c] ˆ w[wCount++]; } 4.2 AES Decryption Operation Here is Java pseudo-code for the inverse cipher. The various steps must be carried out in reverse order. These are arranged into rounds as with encryption, but the functions in each round are in a slightly different order than the order used in encryption. The AES specification has also supplied an equivalent inverse cipher in which the individual parts of each round are in the same order as with encryption. This might make a hardware implementation easier, but I have not used it here. Constants: int Nb = 4; // but it might change someday int Nr = 10, 12, or 14; // rounds, for Nk = 4, 6, or 8 Inputs: array in of 4*Nb bytes // input ciphertext array out of 4*Nb bytes // output plaintext array w of 4*Nb*(Nr+1) bytes // expanded key Internal work array: state, 2-dim array of 4*Nb bytes, 4 rows and Nb cols Algorithm: void InvCipher (byte[] in, byte[] out, byte[] w) { byte[][] state = new byte[4][Nb]; state = in; // actual component-wise copy AddRoundKey (state, w, Nr*Nb, (Nr+1)*Nb - 1); for (int round = Nr-1; round >= 1; round--) { Dept. of CSE, RVCE 15
  • AES Algorithm InvShiftRows (state); InvSubBytes (state); AddRoundKey (state, w, round*Nb, (round+1)*Nb-1); InvMixColumns (state); } InvShiftRows (state); InvSubBytes (state); AddRoundKey (state, w, 0, Nb - 1); out = state; // component-wise copy There are four operations in AES Decryption. These are exact reverse of operations of Encryption. They are, 1) InvSubBytes 2) InvShiftRows 3) InvAddRoundKey 4) InvMixColumns 4.2.1 InvSubBytes The table of the inverse SubBytes transformation could be generated using the inverse of the formula that is used in section 4.2.1. The Java pseudo-code for this part is now very simple, using the InvSbox array defined above: void InvSubBytes (byte[][] state) { for (int row = 0; row < 4; row++) for (int col = 0; col < Nb; col++) state[row][col] = InvSbox[state[row][col]]; } Dept. of CSE, RVCE 16
  • AES Algorithm Figure(7) Shows InvSbox values Figure(7) Shows InvSbox values 4.2.2 InvShiftRows This just does the inverse of ShiftRows: doing a left circular shift of rows 1, 2, and 3, by amounts of 1, 2, and 3 bytes. The actual Java code below does this. void InvShiftRows(byte[][] state) { byte[] t = new byte[4]; for (int r = 1; r < 4; r++) { for (int c = 0; c < Nb; c++) t[(c + r)%Nb] = state[r][c]; for (int c = 0; c < Nb; c++) state[r][c] = t[c]; } } 4.2.3 InvAddRoundKey Since the AES specification uses a parameterized AddRoundKey() function, it is its own inverse, using the parameters in the opposite order. In implementation just Dept. of CSE, RVCE 17
  • AES Algorithm lets AddRoundKey() exclusive-or in another 16 bytes every time it is called, so it need a slightly different function, where wCount is initialized to 4*Nb*(Nr+1): void InvAddRoundKey(byte[][] state) { for (int c = Nb - 1; c >= 0; c--) for (int r = 3; r >= 0 ; r--) state[r][c] = state[r][c] ˆ w[--wCount]; } 4.2.4 InvMixColumns The MixColumns() function was carefully constructed so that it has an inverse. I will add in the theory of this here (or elsewhere) later. For now, it suffices to say that the function multiplied each column by the inverse polynomial of a(x): A-1(x) = (0b) x3 + (0d) x2 + (09)x + (0e) The resulting function, when simplified, takes the following form in Java pseudo-code, whereas before # indicates multiplication in the field: void InvMixColumns(byte[][] s) { byte[] sp = new byte[4]; for (int c = 0; c < 4; c++) { sp[0] = (0x0e # s[0][c]) ˆ (0x0b # s[1][c]) ˆ (0x0d # s[2][c]) ˆ (0x09 # s[3][c]); sp[1] = (0x09 # s[0][c]) ˆ (0x0e # s[1][c]) ˆ (0x0b # s[2][c]) ˆ (0x0d # s[3][c]); sp[2] = (0x0d # s[0][c]) ˆ (0x09 # s[1][c]) ˆ (0x0e # s[2][c]) ˆ (0x0b # s[3][c]); sp[3] = (0x0b # s[0][c]) ˆ (0x0d # s[1][c]) ˆ (0x09 # s[2][c]) ˆ (0x0e # s[3][c]); for (int i = 0; i < 4; i++) s[i][c] = sp[i]; } } Dept. of CSE, RVCE 18
  • AES Algorithm 4.3 Key Expansion Operation In a simple cipher, one might exclusive-or the key with the plaintext. Such a step is easily reversed by another exclusive-or of the same key with the ciphertext. In the case of the AES, there are a number of rounds, each needing its own key, so the actual key is “stretched out” and transformed to give portions of key for each round. This is the key expansion that is the topic of this section. The key expansion routine, as part of the overall AES algorithm, takes an input key (denoted key below) of 4*Nk bytes, or Nk 32-bit words. Nk has value either 4, 6, or 8. The output is an expanded key (denoted w below) of 4*Nb*(Nr+1) bytes, where Nb is always 4 and Nr is the number of rounds in the algorithm, with Nr equal 10 in case Nk is 4, Nr equal 12 in case Nk is 6, and Nr equal 14 in case Nk is 8. The key expansion routine below states most of the actions in terms of words or 4-byte units, since the AES specification itself emphasizes words, but my implementation uses bytes exclusively. Expanded Key Sizes in Words: Key Length Number of Rounds Exp. Key Size (Nk words) (Nr) (Nb(Nr+1) words) 4 10 44 6 12 52 8 14 60 Constants: int Nb = 4; // but it might change someday Inputs: int Nk = 4, 6, or 8; // the number of words in the key array key of 4*Nk bytes or Nk words // input key Output: array w of Nb*(Nr+1) words or 4*Nb*(Nr+1) bytes // expanded key Algorithm: void KeyExpansion(byte[] key, word[] w, int Nw) { int Nr = Nk + 6; w = new byte[4*Nb*(Nr+1)]; int temp; Dept. of CSE, RVCE 19
  • AES Algorithm int i = 0; while ( i < Nk) { w[i] = word(key[4*i], key[4*i+1], key[4*i+2], key[4*i+3]); i++; } i = Nk; while(i < Nb*(Nr+1)) { temp = w[i-1]; if (i % Nk == 0) temp = SubWord(RotWord(temp)) ˆ Rcon[i/Nk]; else if (Nk > 6 && (i%Nk) == 4) temp = SubWord(temp); w[i] = w[i-Nk] ˆ temp; i++; } } Dept. of CSE, RVCE 20
  • AES Algorithm 5. Implementation Detail To demonstrate AES algorithm, we implemented a client server application. The features of client server application are,  Client can connect to sever using Socket() by inputting IP address of server and a particular port.  Client can browse a file to send and encrypt it using his choice key. To encrypt it calls the encrypt() method of AES class. Then send it to server in byte[] format.  Server read bytes and stores in specific file. Then decrypt it using same key used for encryption by calling decrypt() method of AES class.  We used Java Swings to create GUI. The encrypt(byte[] in, byte[] key) method uses following functions to generate cipher text.  generateSubkeys(byte[] key) method used for key expansion.  encryptBloc(byte[] bloc) method used for encrypt block of data.  encryptBloc(byte[] bloc) method in turn uses SubBytes(), ShiftRows(), MixColumns(), and AddRoundKey() methods. For last round, not uses MixColumns() method.  The output of overall operation is cipher text in the format of byte[]. The decrypt(byte[] in, byte[] key) method uses following functions to generate original plain text.  generateSubkeys(byte[] key) method used for key expansion.  decryptBloc(byte[] bloc) method used for decrypt block of data.  decryptBloc(byte[] bloc) method in turn uses InvSubBytes(), InvShiftRows(), InvAddRoundKey() and InvMixColumns() methods. For last round, not uses InvMixColumns() method.  The output of overall operation is cipher text in the format of byte[]. Dept. of CSE, RVCE 21
  • AES Algorithm 6. Conclusion The Advanced Encryption Technique was implemented successfully using ‘Java’ language. Various data messages were encrypted using different keys and varying key sizes. The original data was properly retrieved via decryption of the cipher text. The modifications brought about in the code was tested and proved to be accurately encrypting and decrypting the data messages with even higher security and immunity against the unauthorized users. 6.1 Limitation  The successful attack against AES data encryption has been side channel attacks, which don’t attack the actual AES cipher text, rather than its implementation.  Since it drives on blocks of 128 bits it requires more processing for large data. 6.2 Further Enhancement  Instead of implementing it as Software, we can implement it as Hardware.  Speed up the processing of Encryption and Decryption. Dept. of CSE, RVCE 22
  • AES Algorithm References  Books 1) “Neal R. Wagner “, “The Laws of Cryptography with Java Code”, ”2003” . 2) “Williams Stallings”, “Network Security Essentials Applications and Standards”, “PEARSON”, “4th Edition” , “978-0-13-610805-4”.  Websites 1) http://www.snippetbank.net/detail/snippetdetail/3-java/6-network/310File-Transfer-Example-Using-Socket.html , 23/04/2013 2) http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjd k/6-b14/sun/misc/BASE64Encoder.java , 23/04/2013 3) http://n3vrax.wordpress.com/2011/08/14/aesrijndael-javaimplementation/ , 23/04/2013 Dept. of CSE, RVCE 23
  • AES Algorithm Appendices Appendix A: Source Code AES.java: public class AES { private static int Nb, Nk, Nr; private static byte[][] w; private static int[] sbox = { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, Dept. of CSE, RVCE 24
  • AES Algorithm 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }; private static int[] inv_sbox = { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, Dept. of CSE, RVCE 25
  • AES Algorithm 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D }; private static int Rcon[] = { 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, Dept. of CSE, RVCE 26
  • AES Algorithm 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb }; 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; } private static byte[][] generateSubkeys(byte[] key) { byte[][] tmp = new byte[Nb * (Nr + 1)][4]; int i = 0; while (i < Nk) { tmp[i][0] = key[i * 4]; tmp[i][1] = key[i * 4 + 1]; tmp[i][2] = key[i * 4 + 2]; tmp[i][3] = key[i * 4 + 3]; i++; } i = Nk; while (i < Nb * (Nr + 1)) { byte[] temp = new byte[4]; for(int k = 0;k<4;k++) temp[k] = tmp[i-1][k]; if (i % Nk == 0) { temp = SubWord(rotateWord(temp)); temp[0] = (byte) (temp[0] ^ (Rcon[i / Nk] & 0xff)); Dept. of CSE, RVCE 27
  • AES Algorithm } else if (Nk > 6 && i % Nk == 4) { temp = SubWord(temp); } tmp[i] = xor_func(tmp[i - Nk], temp); i++; } return tmp; } private static byte[] SubWord(byte[] in) { byte[] tmp = new byte[in.length]; for (int i = 0; i < tmp.length; i++) tmp[i] = (byte) (sbox[in[i] & 0x000000ff] & 0xff); return tmp; } private static byte[] rotateWord(byte[] input) { byte[] tmp = new byte[input.length]; tmp[0] = input[1]; tmp[1] = input[2]; tmp[2] = input[3]; tmp[3] = input[0]; return tmp; } private static byte[][] AddRoundKey(byte[][] state, byte[][] w, int round) { byte[][] tmp = new byte[state.length][state[0].length]; for (int c = 0; c < Nb; c++) { for (int l = 0; l < 4; l++) tmp[l][c] = (byte) (state[l][c] ^ w[round * Nb + c][l]); Dept. of CSE, RVCE 28
  • AES Algorithm } return tmp; } private static byte[][] SubBytes(byte[][] state) { byte[][] tmp = new byte[state.length][state[0].length]; for (int row = 0; row < 4; row++) for (int col = 0; col < Nb; col++) tmp[row][col] = (byte) (sbox[(state[row][col] & 0x000000ff)] & 0xff); return tmp; } private static byte[][] InvSubBytes(byte[][] state) { for (int row = 0; row < 4; row++) for (int col = 0; col < Nb; col++) state[row][col] = (byte)(inv_sbox[(state[row][col] & 0x000000ff)]&0xff); return state; } private static byte[][] ShiftRows(byte[][] state) { byte[] t = new byte[4]; for (int r = 1; r < 4; r++) { for (int c = 0; c < Nb; c++) t[c] = state[r][(c + r) % Nb]; for (int c = 0; c < Nb; c++) state[r][c] = t[c]; } return state; } private static byte[][] InvShiftRows(byte[][] state) { Dept. of CSE, RVCE 29
  • AES Algorithm byte[] t = new byte[4]; for (int r = 1; r < 4; r++) { for (int c = 0; c < Nb; c++) t[(c + r)%Nb] = state[r][c]; for (int c = 0; c < Nb; c++) state[r][c] = t[c]; } return state; } private static byte[][] InvMixColumns(byte[][] s){ int[] sp = new int[4]; byte b02 = (byte)0x0e, b03 = (byte)0x0b, b04 = (byte)0x0d, b05 = (byte)0x09; for (int c = 0; c < 4; c++) { sp[0] = FFMul(b02, s[0][c]) ^ FFMul(b03, s[1][c]) ^ FFMul(b04,s[2][c]) ^ FFMul(b05,s[3][c]); sp[1] = FFMul(b05, s[0][c]) ^ FFMul(b02, s[1][c]) ^ FFMul(b03,s[2][c]) ^ FFMul(b04,s[3][c]); sp[2] = FFMul(b04, s[0][c]) ^ FFMul(b05, s[1][c]) ^ FFMul(b02,s[2][c]) ^ FFMul(b03,s[3][c]); sp[3] = FFMul(b03, s[0][c]) ^ FFMul(b04, s[1][c]) ^ FFMul(b05,s[2][c]) ^ FFMul(b02,s[3][c]); for (int i = 0; i < 4; i++) s[i][c] = (byte)(sp[i]); } return s; } private static byte[][] MixColumns(byte[][] s){ int[] sp = new int[4]; byte b02 = (byte)0x02, b03 = (byte)0x03; for (int c = 0; c < 4; c++) { sp[0] = FFMul(b02, s[0][c]) ^ FFMul(b03, s[1][c]) ^ s[2][c] ^ s[3][c]; Dept. of CSE, RVCE 30
  • AES Algorithm sp[1] = s[0][c] ^ FFMul(b02, s[1][c]) ^ FFMul(b03, s[2][c]) ^ s[3][c]; sp[2] = s[0][c] ^ s[1][c] ^ FFMul(b02, s[2][c]) ^ FFMul(b03, s[3][c]); sp[3] = FFMul(b03, s[0][c]) ^ s[1][c] ^ s[2][c] ^ FFMul(b02, s[3][c]); for (int i = 0; i < 4; i++) s[i][c] = (byte)(sp[i]); } return s; } public static byte FFMul(byte a, byte b) { byte aa = a, bb = b, r = 0, t; while (aa != 0) { if ((aa & 1) != 0) r = (byte) (r ^ bb); t = (byte) (bb & 0x80); bb = (byte) (bb << 1); if (t != 0) bb = (byte) (bb ^ 0x1b); aa = (byte) ((aa & 0xff) >> 1); } return r; } public static byte[] encryptBloc(byte[] in) { byte[] tmp = new byte[in.length]; byte[][] state = new byte[4][Nb]; for (int i = 0; i < in.length; i++) state[i / 4][i % 4] = in[i%4*4+i/4]; state = AddRoundKey(state, w, 0); for (int round = 1; round < Nr; round++) { state = SubBytes(state); Dept. of CSE, RVCE 31
  • AES Algorithm state = ShiftRows(state); state = MixColumns(state); state = AddRoundKey(state, w, round); } state = SubBytes(state); state = ShiftRows(state); state = AddRoundKey(state, w, Nr); for (int i = 0; i < tmp.length; i++) tmp[i%4*4+i/4] = state[i / 4][i%4]; return tmp; } public static byte[] decryptBloc(byte[] in) { byte[] tmp = new byte[in.length]; byte[][] state = new byte[4][Nb]; for (int i = 0; i < in.length; i++) state[i / 4][i % 4] = in[i%4*4+i/4]; state = AddRoundKey(state, w, Nr); for (int round = Nr-1; round >=1; round--) { state = InvSubBytes(state); state = InvShiftRows(state); state = AddRoundKey(state, w, round); state = InvMixColumns(state); } state = InvSubBytes(state); state = InvShiftRows(state); state = AddRoundKey(state, w, 0); for (int i = 0; i < tmp.length; i++) tmp[i%4*4+i/4] = state[i / 4][i%4]; Dept. of CSE, RVCE 32
  • AES Algorithm return tmp; } public static byte[] encrypt(byte[] in,byte[] key){ Nb = 4; Nk = key.length/4; Nr = Nk + 6; int lenght=0; byte[] padding = new byte[1]; int i; lenght = 16 - in.length % 16; padding = new byte[lenght]; padding[0] = (byte) 0x80; for (i = 1; i < lenght; i++) padding[i] = 0; byte[] tmp = new byte[in.length + lenght]; byte[] bloc = new byte[16]; w = generateSubkeys(key); int count = 0; for (i = 0; i < in.length + lenght; i++) { if (i > 0 && i % 16 == 0) { bloc = encryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i - 16, bloc.length); } if (i < in.length) bloc[i % 16] = in[i]; else{ Dept. of CSE, RVCE 33
  • AES Algorithm bloc[i % 16] = padding[count % 16]; count++; } } if(bloc.length == 16){ bloc = encryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i - 16, bloc.length); } return tmp; } public static byte[] decrypt(byte[] in,byte[] key){ int i; byte[] tmp = new byte[in.length]; byte[] bloc = new byte[16]; Nb = 4; Nk = key.length/4; Nr = Nk + 6; w = generateSubkeys(key); for (i = 0; i < in.length; i++) { if (i > 0 && i % 16 == 0) { bloc = decryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i - 16, bloc.length); } if (i < in.length) bloc[i % 16] = in[i]; } bloc = decryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i - 16, bloc.length); tmp = deletePadding(tmp); Dept. of CSE, RVCE 34
  • AES Algorithm return tmp; } private static byte[] deletePadding(byte[] input) { int count = 0; int i = input.length - 1; while (input[i] == 0) { count++; i--; } byte[] tmp = new byte[input.length - count - 1]; System.arraycopy(input, 0, tmp, 0, tmp.length); return tmp; } } Client.Java: /* * In this client/server example, the client sends a file to the server. */ import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; public class Client extends JFrame implements ActionListener { public static Client clientForm = new Client(); private JTextField txtFile; AES aes = new AES(); Dept. of CSE, RVCE 35
  • AES Algorithm public long startTime; public long endTime; public long totalTime; PasswordDialog p=new PasswordDialog(); public static JTextField txtip; String str1 = new String(); public static void main(String args[]){ // Create and display the client form clientForm.Display(); } public void Display(){ JFrame frame = new JFrame(); frame.setTitle("Client"); frame.setVisible(true); frame.setSize(100,100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GridLayout layout = new GridLayout(3,2,3,10); JMenuBar mymenu = new JMenuBar(); mymenu.setOpaque(true); mymenu.setBackground(new Color(154, 165, 127)); mymenu.setPreferredSize(new Dimension(100,20)); frame.setJMenuBar(mymenu); JLabel lblip = new JLabel("IP Address"); txtip = new JTextField(); txtip.setPreferredSize(new Dimension(150,30)); JLabel lblFile = new JLabel("Filename:"); txtFile = new JTextField(); txtFile.setPreferredSize(new Dimension(150,30)); JButton btnTransfer = new JButton("Transfer"); Dept. of CSE, RVCE 36
  • AES Algorithm btnTransfer.addActionListener(this); JButton btnExit = new JButton("Exit"); btnExit.addActionListener(new Quit()); JPanel mainPanel = new JPanel(); mainPanel.setLayout(layout); mainPanel.add(lblip); mainPanel.add(txtip); mainPanel.add(lblFile); mainPanel.add(txtFile); mainPanel.add(btnTransfer); mainPanel.add(btnExit); frame.getContentPane().add(mainPanel); frame.pack(); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { /* File Open Dialog box allows the user to select a file */ JFileChooser fileDlg = new JFileChooser(); fileDlg.showOpenDialog(this); String filename = fileDlg.getSelectedFile().getAbsolutePath(); txtFile.setText(filename); try{ /* Try to connect to the server on localhost, port 5555 */ Socket sk = new Socket(txtip.getText(), 5555); JOptionPane.showMessageDialog(this, "Connected"); OutputStream output = sk.getOutputStream(); /* Send filename to server */ OutputStreamWriter outputStream = new Dept. of CSE, RVCE 37
  • AES Algorithm OutputStreamWriter(sk.getOutputStream()); outputStream.write(fileDlg.getSelectedFile().getName() + "n"); outputStream.flush(); /* Get reponse from server */ BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream())); String serverStatus = inReader.readLine(); // Read the first line /* If server is ready, send the file */ if ( serverStatus.equals("READY") ){ byte[] buffer = new byte[sk.getSendBufferSize()]; int bytesRead = 0; String temp=new String();; ReadFileString rfs1=new ReadFileString(); temp=rfs1.rfs(filename); str1 = PasswordDialog.password(0); byte[] key=str1.getBytes(); byte[] input=temp.getBytes(); startTime = System.currentTimeMillis(); byte[] enc=AES.encrypt(input, key); endTime = System.currentTimeMillis(); totalTime = endTime - startTime; JOptionPane.showMessageDialog(this,"Time taken to Encrypt: "+totalTime+" ms "); //temp = new BASE64Encoder().encode(temp.getBytes()); FileOutputStream wr = new FileOutputStream("C://Users/SHREEKANT/Desktop/AES/clenc.txt"); wr.write(enc); wr.close(); FileInputStream file = new Dept. of CSE, RVCE 38
  • AES Algorithm FileInputStream("C://Users/SHREEKANT/Desktop/AES/clenc.txt"); while((bytesRead = file.read(buffer))>0) { output.write(buffer,0,bytesRead); } output.close(); file.close(); sk.close(); JOptionPane.showMessageDialog(this, transmitted : "+ enc.length ); "Transfer complete:nTotal } } catch (Exception ex){ /* Catch any errors */ JOptionPane.showMessageDialog(this, ex.getMessage()); } } } class Quit implements ActionListener { public void actionPerformed (ActionEvent e) { System.exit(0); } } Server.java: /* * Server waits for a connection to be established by client * Dept. of CSE, RVCE 39
  • AES Algorithm */ import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import javax.swing.JOptionPane; public class Server extends JFrame implements ActionListener { public static String filename; public static String temp; AES aes = new AES(); public long startTime; public long endTime; public long totalTime; PasswordDialog p=new PasswordDialog(); String str11 = new String(); public String decr; public static RandomAccessFile f; private static JTextArea txtEnc; private static JTextArea txtDec; public static void main(String args[]){ try{ Server s = new Server(); System.out.println("Server running..."); JOptionPane.showMessageDialog(s,"Server Running"); // Listen on port 5555 Dept. of CSE, RVCE 40
  • AES Algorithm ServerSocket server = new ServerSocket(5555); // Accept the sk Socket sk = server.accept(); System.out.println("Server accepted client"); JOptionPane.showMessageDialog(s,"Server accepted client"); InputStream input = sk.getInputStream(); BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream())); BufferedWriter outReader = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())); // Read the filename filename = inReader.readLine(); if ( !filename.equals("") ){ // Reply back to client with READY status outReader.write("READYn"); outReader.flush(); } // Create a new file in the tmp directory using the filename FileOutputStream wr = new FileOutputStream(new File("C://Users/SHREEKANT/Desktop/AES/enc" + filename)); byte[] buffer = new byte[sk.getReceiveBufferSize()]; int bytesReceived = 0; while((bytesReceived = input.read(buffer))>0){ /* Write to the file */ wr.write(buffer,0,bytesReceived); } JOptionPane.showMessageDialog(s,"Encrypted File Saved sucessfullynPath:C://Users/SHREEKANT/Desktop/AES/enc"+ filename); Dept. of CSE, RVCE 41
  • AES Algorithm s.Servergui(); try { f = RandomAccessFile("C://Users/SHREEKANT/Desktop/AES/enc" new + filename,"r"); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } long longlength = 0; try { longlength = f.length(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int length = (int) longlength; // Read file and return data byte[] data = new byte[length]; try { f.readFully(data); f.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } temp=new String(data); txtEnc.setText(temp); } catch(Exception e){ Dept. of CSE, RVCE 42
  • AES Algorithm System.err.println(e); } } void Servergui() { JFrame frame = new JFrame(); frame.setTitle("Server"); frame.setVisible(true); frame.setSize(150,100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GridLayout layout = new GridLayout(3,1,3,3); JMenuBar mymenu = new JMenuBar(); mymenu.setOpaque(true); mymenu.setBackground(new Color(154, 165, 127)); mymenu.setPreferredSize(new Dimension(30,20)); frame.setJMenuBar(mymenu); JLabel lblEnc = new JLabel("Encrypted Text"); lblEnc.setPreferredSize(new Dimension(5,15)); txtEnc = new JTextArea(5,10); txtEnc.setLineWrap(true); txtEnc.setEditable(false); txtEnc.setPreferredSize(new Dimension(5,15)); JScrollPane scrollPane1= new JScrollPane ( txtEnc,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORI ZONTAL_ SCROLLBAR_ALWAYS); JLabel lblDec = new JLabel("Decrypted Text"); lblDec.setPreferredSize(new Dimension(5,15)); txtDec= new JTextArea(5,10); txtDec.setLineWrap(true); Dept. of CSE, RVCE 43
  • AES Algorithm txtDec.setEditable(false); txtDec.setPreferredSize(new Dimension(5,15)); JScrollPane scrollPane11= new JScrollPane( txtDec,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HOR IZONTAL_ SCROLLBAR_ALWAYS); JButton btnDec = new JButton("Decrypt"); btnDec.setPreferredSize(new Dimension(5,15)); btnDec.addActionListener(this); JButton btnExit = new JButton("Exit"); btnDec.setPreferredSize(new Dimension(5,15)); btnExit.addActionListener(new Quit()); JPanel mainPanel = new JPanel(); mainPanel.setLayout(layout); mainPanel.add(lblEnc); //mainPanel.add(txtEnc); mainPanel.add(scrollPane1); mainPanel.add(lblDec); // mainPanel.add(txtDec); mainPanel.add(scrollPane11); mainPanel.add(btnDec); mainPanel.add(btnExit); frame.getContentPane().add(mainPanel); frame.pack(); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stu try { Dept. of CSE, RVCE 44
  • AES Algorithm f = new RandomAccessFile("C://Users/SHREEKANT/Desktop/AES/enc" + filename,"r"); } catch (FileNotFoundException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } long longlength = 0; try { longlength = f.length(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int length = (int) longlength; // Read file and return data byte[] data = new byte[length]; try { f.readFully(data); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } temp=new String(data); txtEnc.setText(temp); str11 = PasswordDialog.password(1); byte[] key=str11.getBytes(); Dept. of CSE, RVCE 45
  • AES Algorithm try{ startTime = System.currentTimeMillis(); byte[] dec=AES.decrypt(data, key); endTime = System.currentTimeMillis(); totalTime = endTime - startTime; temp=new String(dec); txtDec.setText(temp); JOptionPane.showMessageDialog(this,"Time taken to Decrypt: "+totalTime+" ms "); } catch(Exception ex) { JOptionPane.showMessageDialog(this,ex.getMessage()); } } } ReadFileString: import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFileString { public String rfs (String path) throws Exception { try{ String entireFileText = new Scanner(new File(path)) .useDelimiter("A").next(); return entireFileText; } catch(Exception e){ Dept. of CSE, RVCE 46
  • AES Algorithm System.err.println(e); return null; } } } //Imports are listed in full to show what's being used //could just import javax.swing.* and java.awt.* etc.. import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JTextArea; import javax.swing.JPasswordField; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.GridLayout; import java.util.Arrays; import java.awt.EventQueue; PasswordDialog.java: public class PasswordDialog { public static String password(int i) { JFrame guiFrame = new JFrame(); JPanel userPanel = new JPanel(); userPanel.setLayout(new GridLayout(2,2)); if(i==0) { JLabel passwordLbl = new JLabel("Enter Key to Encrypt:"); userPanel.add(passwordLbl); } Dept. of CSE, RVCE 47
  • AES Algorithm else{ JLabel passwordLbl = new JLabel("Enter Key to Decrypt:"); userPanel.add(passwordLbl); } JPasswordField passwordFld = new JPasswordField(); userPanel.add(passwordFld); int input = JOptionPane.showConfirmDialog(guiFrame, userPanel, "AES Key",JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); String enteredPassword =new String(passwordFld.getPassword()); return enteredPassword; } } Dept. of CSE, RVCE 48
  • AES Algorithm APPENDIX B: Snap shots Client side Snap shots: Dept. of CSE, RVCE 49
  • AES Algorithm Server side Snap Shots: Dept. of CSE, RVCE 50