I have for a few days reading this and other tutorials about javax.crypto
Using block modes and initialisation vectors in Java
My test code below is a Client who send data to a Server.
I read about different block modes and the CFB8 stream mode seem to be working because i split arbitrary size files up in chunks. Every chunk is 0.5MB except for the last chunk that are smaller, they are sent one after another to the Server that put the file back together.
I have a few questions:
1) Should i use Asymmetric cryptography publ/priv keys to send the SecretKeySpec password and the IV to the server before i start the transfer?
2) What are the SecretKeySpec password used for, protect the IV?
THE CLIENT encrypt data
Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec("password12345678".getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
out.write(iv); //Send IV to Server
out.flush();
// THE ENCRYPTET STREAM
cos = new CipherOutputStream(out, cipher);
while ((val = byteArrayInputStream.read(buffer, 0, 1024)) > 0) {
cos.write(buffer, 0, val);
cos.flush();
}
cipher.doFinal()
THE SERVER decrypt data
byte[] iv = new byte[16];
in.read(iv);
Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec("password12345678".getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
cos = new CipherInputStream(in, cipher);
while (offset < tmpBuffer.length && (numRead=cos.read(tmpBuffer, offset, tmpBuffer.length-offset)) >= 0) {
offset += numRead;
savedFileSize = savedFileSize + numRead;
}
// CREATE HASH FROM THE DOWNLOAD CHUNK PART
String retCrC = DoEncryption.getCRC32ChecksumFromArray(tmpBuffer);
String hash2 = Long.toHexString( Long.parseLong(retCrC) );
// TEST SO THE REMOTE HASH MATCH THE LOCAL HASH
if(!hash1.equals(hash2)){
...
This is broadly how SSL works, albeit usually in reverse. Any reason you couldn’t use SSL/TLS instead? Generating your own secure transfer protocol is not a trivial undertaking.