rc4.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. Name: Ajinkya Arun Gurav
  3. Div : H Roll No:21
  4. GR No : 121237
  5. Subject : Network Security Lab
  6. Lab 5: Implement encryption and decrypzztion using RC4 Algorithm.
  7. */
  8. import java.io.*;
  9. class rc4
  10. {
  11. public static void main(String args[])
  12. {
  13. int i=0,j=0,temp=0;
  14. String ptxt=null,key=null;
  15. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  16. try{
  17. System.out.println("Enter plaintext");
  18. ptxt=br.readLine();
  19. System.out.println("Enter keytext\t\t");
  20. key=br.readLine();
  21. }
  22. catch(Exception e)
  23. {
  24. System.out.println("Exception is: "+e.getLocalizedMessage());
  25. }
  26. int s[]=new int[256];
  27. int k[]=new int[256];
  28. int cipher[]=new int[ptxt.length()];
  29. int decrypt[]=new int[ptxt.length()];
  30. char ptxtc[]=ptxt.toCharArray();
  31. char keyc[]=key.toCharArray();
  32. int ptxti[]=new int[ptxt.length()];
  33. int keyi[]=new int[key.length()];
  34. for(i=0;i<ptxt.length();i++)
  35. {
  36. ptxti[i]=ptxtc[i];
  37. }
  38. for(i=0;i<key.length();i++)
  39. {
  40. keyi[i]=keyc[i];
  41. }
  42. for(i=0;i<256;i++)
  43. {
  44. s[i]=i;
  45. k[i]=keyi[i%key.length()];
  46. }
  47. j=0;
  48. for(i=0;i<255;i++)
  49. {
  50. j=(j+s[i]+k[i])%256;
  51. temp=s[i];
  52. s[i]=s[j];
  53. s[j]=temp;
  54. }
  55. i=0;
  56. j=0;
  57. int z=0;
  58. for(int l=0;l<ptxt.length();l++)
  59. {
  60. i=(l+1)%256;
  61. j=(j+s[i])%256;
  62. temp=s[i];
  63. s[i]=s[j];
  64. s[j]=temp;
  65. z=s[(s[i]+s[j])%256];
  66. cipher[l]=z^ptxti[l];
  67. decrypt[l]=z^cipher[l];
  68. }
  69. System.out.println("ENCRYPTED:");
  70. disp(cipher);
  71. System.out.println("DECRYPTED:");
  72. disp(decrypt);
  73. }
  74. private static void disp(int[] txtcipher) {
  75. char StrToChar[]=new char[txtcipher.length];
  76. for(int increment=0;increment<txtcipher.length;increment++)
  77. {
  78. StrToChar[increment]=(char)txtcipher[increment];
  79. System.out.print(StrToChar[increment]);
  80. }
  81. System.out.println("\n");
  82. }
  83. }
  84. /*
  85. Enter plaintext
  86. ajinkya
  87. Enter keytext
  88. abc
  89. ENCRYPTED:
  90. ¬÷°G3¦?
  91. DECRYPTED:
  92. ajinkya
  93. */