Code with Finding: |
class SharedKeyCryptoComm {
public static boolean send(byte[] msgbytes, OutputStream os, Cipher c, SecretKey sk,
BigInteger sendNonce) throws ConnectionException {
int blockSize = c.getBlockSize();
SecureRandom sr = createSecureRandom();
try {
//iv and msg
byte[] iv = createIV(sr, blockSize);
IvParameterSpec ivp = new IvParameterSpec(iv);
try {
c.init(Cipher.ENCRYPT_MODE, sk, ivp);
}
catch (Exception e) {/*This cannot happen*/}
byte[] encmsg = null;
try {
encmsg = c.doFinal(msgbytes);
} catch (Exception e) { //exception should not happen...
e.printStackTrace();
}
byte[] encmsglen = ByteBuffer.allocate(4).putInt(encmsg.length).array();
byte[] sendNonceArray = sendNonce.toByteArray();
byte[] sendNonceArrayMsg = Arrays.copyOf(sendNonceArray, NONCE_LENGTH);
byte[] totalmsg = new byte[NONCE_LENGTH + iv.length + encmsglen.length + msgbytes.length];
//nonce, iv, msglen, and msgbytes.
System.arraycopy(sendNonceArrayMsg, 0, totalmsg, 0, NONCE_LENGTH);
System.arraycopy(iv, 0, totalmsg, NONCE_LENGTH, iv.length);
System.arraycopy(encmsglen, 0, totalmsg, NONCE_LENGTH + iv.length, encmsglen.length);
System.arraycopy(msgbytes, 0, totalmsg, NONCE_LENGTH + iv.length + encmsglen.length, msgbytes.length);
//get checksum
byte[] checksum = Hash.generateChecksum(totalmsg);
// zero out totalmsg.
Arrays.fill(totalmsg, (byte)0x00);
os.write(checksum); //128 bits
os.write(sendNonceArrayMsg);
os.write(iv);
os.write(encmsglen);
os.write(encmsg);
os.flush();
}
catch (IOException e) {
System.out.println("Error/Timeout sending the message (msg in bytes so it is not printed) ");
System.out.println("Closing the connection");
throw new ConnectionException();
}
return true;
}
}
|