3

I am working on a chat application. The main feature is to send messages in encrypted form and when they reach their destination they can be decrypted. The problem I am having is that the messages are not getting decrypted at their destination but however they reach their destination in encrypted form.

How the code works:

  1. Client A sends message "Hello" to client B...
  2. When Client A clicks on button "Send message" I save that text in a String and then that String is passed along with key and iv to the method Encrypt like this...

    en=enc.encrypt(msg.getBytes(), key.getBytes(), iv.getBytes());
    

    I convert that byte (en) into string and sends it to the other client B.

  3. When I open the other class where I receive the message I get the string (en) and then again converts it into bytes which is passed to the method Decrypt. But whenever I run the project it doesn't work. Tried to do that in try catch but didn't worked either. Maybe because it is already in a big try catch statement already which makes it even more confusing.

My code:

package com.socket;

import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;

public class Encrypt {

  public Encrypt() {
  }

  public static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
      throws Exception {
    int minSize = cipher.getOutputSize(data.length);

    byte[] outBuf = new byte[minSize];

    int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);

    int length2 = cipher.doFinal(outBuf, length1);

    int actualLength = length1 + length2;

    byte[] result = new byte[actualLength];

    System.arraycopy(outBuf, 0, result, 0, result.length);

    return result;
  }

  public static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv)
      throws Exception {

    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
        new CBCBlockCipher(new AESEngine()));

    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);

    aes.init(false, ivAndKey);

    return cipherData(aes, cipher);
  }

  public byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception {

    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
        new CBCBlockCipher(

        new AESEngine()));

    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);

    aes.init(true, ivAndKey);

    return cipherData(aes, plain);
  }
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
  • Your question is an extremely non-specific "fix my code by writing it so that it works". Your question is very poorly formatted which makes me think you didn't spend much time on it. Your excessive use of ellipses also makes me think that you're in over your head. Spend as much time as you can in office hours with your instructor/TA, but you may still fail from being too far behind to be able to catch up. – Nathaniel Waisbrot Jun 08 '13 at 20:09
  • I just tested your encryption/decryption code and it works. Your problem must lie elsewhere. As a result, I've voted to close this question. – Duncan Jones Jun 09 '13 at 07:19
  • Note: you really should have tested your code example before posting it. It took me two minutes to figure out the code worked correctly. A side note on style: don't throw `Exception` from methods, instead only throw the necessary checked exceptions (`IllegalStateException, InvalidCipherTextException`). – Duncan Jones Jun 09 '13 at 07:26
  • i tested the code mate and it was working fine..... but when i use this code in my project i get errors, the string is encrypted but it is not decrypting.... i pass the string that has to be encrypted to this program and then at the receiving client end i pass the encrypted string to the decrypted method and it's not working.... – Syed Hassaan Ali Jun 09 '13 at 09:13
  • @SyedHassaanAli We can't debug your entire program for you. Try and narrow down the area to figure out what is going wrong. Maybe your network sending code is faulty? Try sending in cleartext first, then try ciphertext later. – Duncan Jones Jun 09 '13 at 14:04
  • can i upload the entire project here ?? or if someone want to take a look i can also email you the project.......... – Syed Hassaan Ali Jun 09 '13 at 15:56
  • @SyedHassaanAli No, please don't. We do not fix entire projects on this site. Have you tried my suggestion of just sending cleartext across? Also, if you include my user name with the '@' symbol, I will be notified of your responses. – Duncan Jones Jun 10 '13 at 12:56
  • @DuncanJones thankx for your help mate..... i used this code instead of the above http://stackoverflow.com/questions/10303767/encrypt-and-decrypt-in-java and it workssssssssssssssssss finallyyyyyyyyyyyyyyy – Syed Hassaan Ali Jun 12 '13 at 12:14

1 Answers1

3

You are using String.getBytes() on a regular basis. That's almost certain one location where you make an error. getBytes() is platform dependent, so you may get different bytes on different systems. Furthermore, not all bytes are valid character encodings. So if your key/IV consists of secure random bytes (which they should) then your decryption will fail...sometimes.

The general answer is to convert characters to bytes using a well specified character-encoding (e.g. UTF-8) and bytes to characters using an encoding like base-64 or hexadecimals.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • thankx for your help mate i replaced that code with this one http://stackoverflow.com/questions/10303767/encrypt-and-decrypt-in-java and it worked............. – Syed Hassaan Ali Jun 12 '13 at 12:16
  • You may get some hints from the accepted answer over there, especially regarding character encoding/decoding, but the code there is not safe. Certainly don't use ECB mode. Try my answer [here](http://stackoverflow.com/a/8828196/589259). – Maarten Bodewes Jun 12 '13 at 20:29