ECC_Server.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import java.io.*;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. import java.util.Scanner;
  5. public class ECC_Server {
  6. static long P,A,B,Gx,Gy,N;
  7. public static void main(String[] args) throws IOException
  8. {
  9. long random,Cx=0,Cy=0;
  10. String exchange=null;
  11. int count=1,len=0;
  12. Scanner scan=new Scanner(System.in);
  13. long[] result=new long[2],input=new long[2],SharedSec=new long[2];
  14. System.out.println("Enter P");
  15. P=scan.nextLong();
  16. System.out.println("Enter a");
  17. A=scan.nextLong();
  18. System.out.println("Enter b");
  19. B=scan.nextLong();
  20. System.out.println("Enter Gx");
  21. Gx=scan.nextLong();
  22. System.out.println("Enter Gy");
  23. Gy=scan.nextLong();
  24. System.out.println("Enter N");
  25. N=scan.nextLong();
  26. System.out.println("Enter random number between 1 to "+(N-1));
  27. random=scan.nextLong();
  28. result[0]=Gx;
  29. result[1]=Gy;
  30. for(int i=1;i<random;i++)
  31. {
  32. result=Same_Points_Addition(result);
  33. count++;
  34. }
  35. System.out.print("Public key is: ("+result[0]+",");
  36. System.out.print(result[1]+")\n");
  37. if(result[0]<0)
  38. result[0]=-result[0];
  39. if(result[1]<0)
  40. result[1]=-result[1];
  41. exchange=exchange+""+result[0];
  42. exchange=exchange+""+result[1];
  43. ServerSocket servsocket = new ServerSocket(6009);
  44. System.out.println("Server is ready");
  45. Socket socket = servsocket.accept();
  46. OutputStream outputStream = socket.getOutputStream();
  47. PrintWriter printwriter = new PrintWriter(outputStream, true);
  48. InputStream inputStream = socket.getInputStream();
  49. //Send Data
  50. len=result.length;
  51. outputStream.write(len);
  52. for(int i=0;i<len;i++)
  53. {
  54. outputStream.write((int) result[i]);
  55. }
  56. printwriter.flush();
  57. //Receive Data
  58. len=inputStream.read();
  59. for(int i=0;i<len;i++)
  60. {
  61. input[i]=inputStream.read();
  62. }
  63. //
  64. Cx=input[0];
  65. Cy=input[1];
  66. System.out.println("Partial Key is: ("+Cx+","+Cy+")");
  67. SharedSec[0]=Cx;
  68. SharedSec[1]=Cy;
  69. for(int i=1;i<random;i++)
  70. {
  71. SharedSec=Same_Points_Addition(SharedSec);
  72. }
  73. if(SharedSec[0]<0)
  74. SharedSec[0]=-SharedSec[0];
  75. if(SharedSec[1]<0)
  76. SharedSec[1]=-SharedSec[1];
  77. System.out.println("Shared Secret is ("+SharedSec[0]+","+SharedSec[1]+")");
  78. }
  79. static long[] Same_Points_Addition(long[] input)
  80. {
  81. long[] result=new long[2];
  82. double lambda=0;
  83. long x=input[0],y=input[1];
  84. if(y!=0)
  85. lambda=(((3*(x*x))+A)/(2*y));
  86. result[0]=(long) (((lambda*lambda)-x-x)%P);
  87. result[1]=(long) (((lambda*(x-result[0])-y))%P);
  88. return result;
  89. }
  90. }