RockOn RockOn - 1 year ago 54
Java Question

x.509 Cert - How to generate store file?

Okay so I am working with this code below to teach myself about x.509 certs. My question is, am I supposed to generate a cert or store file somewhere else and then attach the file to the project? Or is the project supposed to generate all of this in the program? My error is that it can't find the store file.

Answer Source

Basically, those two programs expect that the certificates and keystore are already created, with the name and crypt.cer and that those two files are in the folder from which the programs are lauched.

To generate those file, you can use keytool from your java distribution to create a keystore and a certificate and then, from that, you can export the public cert.

Here is what does the server step by step :

int port = 7999;
ServerSocket server = new ServerSocket(port);
Socket s = server.accept();
ObjectInputStream is = new ObjectInputStream(s.getInputStream());

The server opens a listening socket on port 7999 and expect some content.

//Read the keystore and retrieve the server's private key  
//Default keystore is jks
KeyStore ks = KeyStore.getInstance("jks");
ks.load(new FileInputStream(""), password);
PrivateKey dServer = (PrivateKey)ks.getKey(aliasname, password);

It gets a keystore located in the file called (relative file to where you lauched your program. From that keystore, it gets the private key whose alias is aliasname ("user" in your case).

//Decrypt: server's private key 
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
byte[] in = (byte[]) is.readObject();
cipher.init(Cipher.DECRYPT_MODE, dServer);
byte[] plaintText = cipher.doFinal(in);
System.out.println("The plaintext is: " + new String(plaintText));

It decrypt the content send to the socket by using the private key and print it on the standard output (console typically)

Now for the client :

String host = "localhost";
int port = 7999;
Socket s = new Socket(host, port);

ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());

It connects to the socket on port 7999

 //Client loads server's cert
InputStream inStream = new FileInputStream("crypt.cer");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);

get the public certificate of the server from the file crypt.cer (again relative) Then, it checks the validity of the certificate.

//Get public key from cert
RSAPublicKey eServer = (RSAPublicKey) cert.getPublicKey();

//Encrypt with RSA as key generation algorithm 
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, eServer);
byte[] cipherText = cipher.doFinal(message.getBytes());
System.out.println("Ciphertext: " + cipherText);

This encrypt the message (which the user entered) and send it to the server.