Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
template
Introduction
This software template will use java programming language as a means of demonstration of creating
a network program with ability to securely communication between server and clients in which files
transferred between will be encrypted and checked for integrity.
The communication between client and server will be performed using public key certification for
encryption.
Public-private keypair
Firstly, we will try to generate a random public encryption key pair. The function for public
encryption comes from Java Cryptography Extension (JCE).
TM
The key pair is generated by using KeyPairGenerator. In the sample program, I have create a tool
CipherGenerator for this specific purpose.
The CipherGenerator create a Jkeypair object which function is to create public and private key files.
Key files is then store in form of:
Pseudo code
The pseudo code for CipherGenerator are:
public main(){
1. Generate public key pair files for encryption and session keys
//call keypairgenerate(String algorithm, int keySize, String output)
2. Encrypt a document
// call readKey(String algorithm, String mode, String input) for key value return.
//call cipherGenerator(String algorithm, String mode, Key ke, String input, String output)
with key value and encrypt mode for document encrypt
3. Decrypt a document
//call readKey(String algorithm, String mode, String input) for key value return.
//call cipherGenerator(String algorithm, String mode, Key ke, String input, String output)
with key value and decrypt mode for document decrypt
public static void cipherGenerator(String algorithm, String mode, Key ke, String input, String
output){
//Depend on mode, the String input (file name) document is decrypt or encrypt
// input file name and produce md5 hash value of the file.
Certificate
A digitally signed statement from the issuer saying that the public key of the subject has some
specific value. The certificate store public and private key that is needed for connection between
client and server in SSL. The certificate using in this project is X.509 Certificate format
The certificate using for connection is generated using keytool.exe from Java SDK. Procedure is to
follow command:
Client and Server communicate with each other through SSL connection.
Pseudo code
Server:
public static void main(String[] args){
//retrieve certificate key store and load certificate for SSL connection
//provide function of server to retrieve public key, encrypt and send encrypted document, send
document hash to client
public static void receiveFile( int filesize, int current, InputStream is, CipherGenerator cp){
}
Client
public static void main(String[] args){
//retrieve certificate key store and load certificate for SSL connection
//provide function of client to retrieve encrypted file, decrypt, retrieve hash value, and perform hash
check on the transferred document.
//perform hash check on file take in original and current hash value and compare. If not valid then
the file transfer is unsuccessful
public static void receiveFile( int filesize, int current, InputStream is){
User document
Client.java provides the following function:
1. Retreive the public key from the client and encrypt a document file
1. Client selects sent public key to server (1) and specify the value of the public key file
name
2. Server selects retrieves the public key from the client (1) and specify the document need
to be encrypted (the encrypted document will be named “encrypted.txt”).
3. Server selects Send the encrypted document to client (2)
4. Client selects retrieving and decrypts the encrypted document (2). The decrypted
document will be named “decrypted.txt”
5. Server selects send has value of the sent document (3) to client (user must re-input the
file name)
6. Client select to perform hash check (3) to determine if the file transfer have success or
not (hash check will be perform for “decrypted.txt”).
Program code:
JKeyPair.java
package network;
import java.io.*;
import java.math.*;
import java.security.*;
import java.security.interfaces.*;
import javax.crypto.*;
import javax.crypto.spec.*;
class JKeyPair {
public void getKeysPairs(int keySize, String output, String algorithm) throws Exception {
KeyPairGenerator kg = KeyPairGenerator.getInstance(algorithm);
kg.initialize(keySize);
byte[] ke = priKey.getEncoded();
out.write(ke);
out.close();
file = output+".publ";
ke = pubKey.getEncoded();
out.write(ke);
out.close();
try {
keg.init(keySize);
Key sk = keg.generateKey();
byte[] ke = sk.getEncoded();
out.write(ke);
out.close();
}catch (Exception e) {
System.out.println("Exception: "+e);
return;
CipherGenerator.java
package network;
/**
*/
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import java.io.*;
import java.util.Scanner;
import java.math.*;
/**
*/
public CipherGenerator(){
Key ke = null;
//Option:
System.out.println("1. Generate public key pair files for encryption and session keys");
switch (choice) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
String str=md5(cfile);
break;
jkeypair.getKeysPairs(keySize,output,algorithm);
} catch (Exception e) {
System.out.println("Exception: "+e);
return;
public static Key readKey(String algorithm, String mode, String input) throws Exception {
System.out.println();
System.out.println("Key reading...");
int kl = fis.available();
fis.read(kb);
fis.close();
Key ke = null;
if (mode.equalsIgnoreCase("encrypt")) {
X509EncodedKeySpec pubKeySpec
= new X509EncodedKeySpec(kb);
ke = keyFactory.generatePublic(pubKeySpec);
} else if (mode.equalsIgnoreCase("decrypt")) {
PKCS8EncodedKeySpec priKeySpec
= new PKCS8EncodedKeySpec(kb);
ke = keyFactory.generatePrivate(priKeySpec);
} else
System.out.println();
return ke;
public static void cipherGenerator(String algorithm, String mode, Key ke, String input, String
output) throws Exception {
Cipher cf = Cipher.getInstance(algorithm);
if (mode.equalsIgnoreCase("encrypt"))
cf.init(Cipher.ENCRYPT_MODE,ke);
else if (mode.equalsIgnoreCase("decrypt"))
cf.init(Cipher.DECRYPT_MODE,ke);
else
System.out.println();
int n = fis.read(buf,0,bufSize);
int fisSize = 0;
int fosSize = 0;
while (n!=-1) {
fisSize += n;
fosSize += out.length;
fos.write(out);
n = fis.read(buf,0,bufSize);
fosSize += out.length;
fos.write(out);
fis.close();
fos.close();
System.out.println();
int kl = fis.available();
fis.read(kb);
fis.close();
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(kb,0,kb.length); // hashing
return hashKey;
Server.java
package network;
import java.net.*;
import java.security.*;
import javax.net.ssl.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import java.io.*;
import java.util.Scanner;
import java.math.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
int current = 0;
//retrieve certificate key store and load certificate for SSL connectiion
KeyStore ks = KeyStore.getInstance("JKS");
kmf.init(ks, ctPass);
SSLContext sc = SSLContext.getInstance("TLS");
System.out.println(((X509Certificate) cchain2[i]).getSubjectDN());
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
//Option:
System.out.println("1. Retreive the public key from the client and encrypt a document file");
switch (choice) {
case 0:
quit = true;
break;
case 1:
inputFile = selectFile();
break;
case 2:
sendEFile(os);
break;
case 3:
sendHash(file, w, cp);
break;
os.close();
s.close();
try{
String hashVal = cp.md5(file);
w.write(hashVal);
w.flush();
}catch(Exception e) {
System.out.println("Exception: "+e);
String hash;
hash = r.readLine();
return hash;
return enFile;
public static void receiveFile( int filesize, int current, InputStream is, CipherGenerator cp){
try{
// receive file
do {
bos.write(mybytearray, 0 , current);
bos.flush();
bos.close();
fos.close();
}catch(Exception e) {
System.out.println("Exception: "+e);
return;
try{
//send file
bis.read(mybytearray,0,mybytearray.length);
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}catch(Exception e) {
System.out.println("Exception: "+e);
Client.java
/*
*/
package network;
import java.net.*;
import java.security.*;
import javax.net.ssl.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import java.io.*;
import java.util.Scanner;
import java.math.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class Client {
int current = 0;
//retrieve certificate key store and load certificate for SSL connectiion
tmf.init(keystore);
SSLSocketFactory sf = context.getSocketFactory();
//s.startHandshake();
SSLSession session = ((SSLSocket) s).getSession();
System.out.println(((X509Certificate) cchain[i]).getSubjectDN());
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
//Option:
switch (choice) {
case 1:
break;
case 2:
inputFile = "encrypted.txt";
break;
case 3:
hashCheck(originalHash, currentHash);
break;
os.close();
s.close();
}
public static void hashCheck(String originalHash, String currentHash){
if (originalHash.equals(currentHash)){
else{
String hash;
hash = r.readLine();
return hash;
try{
w.write(hashVal);
w.flush();
}catch(Exception e) {
System.out.println("Exception: "+e);
return sendFile;
System.out.println("Please put your public key to working directory and type it name");
return sendFile;
try{
bis.read(mybytearray,0,mybytearray.length);
//OutputStream os = s.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}catch(Exception e) {
System.out.println("Exception: "+e);
public static void receiveFile( int filesize, int current, InputStream is){
try{
// receive file
current = bytesRead;
do {
bos.write(mybytearray, 0 , current);
bos.flush();
bos.close();
}catch(Exception e) {
System.out.println("Exception: "+e);
return;
}
Reference
Java Tool Tutorials © 2006 Dr. Herong Yang, access: 10/2010, http://www.herongyang.com/jtool/