190 likes | 341 Views
Java Program to Implement RSA Algorithm Yu-Li Chen April, 2002. RSA: public key cryptographic system algorithm of RSA is openly published much slower than encrypting with a secret key provides both confidentiality and digital signing functions
E N D
Java Program to Implement RSA Algorithm Yu-Li Chen April, 2002
RSA: • public key cryptographic system • algorithm of RSA is openly published • much slower than encrypting with a secret key • provides both confidentiality and digital signing functions • mostly used for authentication and exchanging a secret key
The RSA algorithm: • Key generation • Encryption with public key • Decryption with private key
Key generation • Select p,q p and q both prime • Calculate n = p*q • Calculate (n)=(p-1)(q-1) • Select integer gcd ((n),e)=1; 1<e<(n) • Calculate d e*d=1 mod (n) • Public key Kpublic={e,n} • Private key Kprivarte={d,n}
Encryption • Plaintext: M<n • eCiphertext: C=M mode n
Decryption • Ciphertext: C • d • Plaintext: M=C mode n
Objectives: • Write a Java program to implement RSA algorithm • After public key and private key been generated, use Alice/Bob application over TCP to demonstrate encryption and decryption process.
Method: • Alice class: • Generate the public key pair (1024 bit) and send to Bob. • Decrypt the message received from Bob • Bob class: • Receive public key from Alice • Use the public key to encrypt the message • Send the ciphertext to Alice.
Alice: bitLength = 512; certainty = 50; rnd = new SecureRandom(); p = new BigInteger(bitLength, certainty, rnd); q = new BigInteger(bitLength,certainty,rnd); n= p.multiply(q); one= new BigInteger("1"); x = p.subtract(one).multiply(q.subtract(one)); e = new BigInteger("65537"); d = e.modInverse(x);
Alice: Socket clientSocket = new Socket(hostname, 6789); DataOutputStream outToBob =new DataOutputStream(clientSocket.getOutputStream()); outToBob.writeBytes(publicKey + '\n'); clientSocket.close();
Bob: ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromAlice =new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); publicKey = inFromAlice.readLine(); publickyText.setText(publicKey); }
Bob: n= new BigInteger(publicKey); e = new BigInteger("65537"); plaintext=plainText.getText(); m= new BigInteger(plaintext); c = m.modPow(e,n); ciphertext=c.toString();
Bob: Socket clientSocket = new Socket(hostname, 2345); DataOutputStream outToAlice = new DataOutputStream( clientSocket.getOutputStream()); outToAlice.writeBytes(ciphertext); clientSocket.close();
Alice: ServerSocket welcomeSocket = new ServerSocket(2345); while(true) { Socket connectionSocket= welcomeSocket.accept(); BufferedReader inFromBob = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); cipher=inFromBob.readLine(); cipherText.setText(cipher); c= new BigInteger(cipher); m=c.modPow(d,n);