1

hi, i try to implement aes in some open source code messaging application. for encrypted message, its work find to me. but i have difficulty to decrypt back message.

in this class, i can encrypted message and it work fine.

MessageActivity.java

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.message);

    messageView = (TextView) findViewById(R.id.message_view);

    final Button button = (Button) findViewById(R.id.btn_send);
    final EditText message = (EditText) findViewById(R.id.edit_message);

    this.setTitle("Group Chat");

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            String str = message.getText().toString();
            byte[] cipherText = null;
            try {
                cipherText = AESEncryption.encryptText(str, AESEncryption.thisKey());
            } catch (Exception e) {
                e.printStackTrace();
            }
            String msgStr = new String(cipherText);
            addMessage("This phone", str);
            message.setText("");

            // Send to other clients as a group chat message
            for (AllEncompasingP2PClient c : MeshNetworkManager.routingTable.values()) {
                if (c.getMac().equals(MeshNetworkManager.getSelf().getMac()))
                    continue;
                Sender.queuePacket(new Packet(Packet.TYPE.MESSAGE, msgStr.getBytes(), c.getMac(),
                        WiFiDirectBroadcastReceiver.MAC));
            }

        }
    });

Receiver.java

/////////////// this messsage receiver part///////////////////////

byte[] thisMsg = p.getData();
String decryptedText = null;
 try {
 decryptedText = AESEncryption.decryptText(thisMsg, AESEncryption.thisKey());
 } catch (Exception e) {
  e.printStackTrace();
 }

final String message = p.getSenderMac() + " says:\n" + decryptedText;
final String msg = new String(p.getData());
final String name = p.getSenderMac();

//////////////////////////////////////


if (!MeshNetworkManager.routingTable.contains(p.getSenderMac())) {
    /*
     * Update your routing table if for some reason this
    * guy isn't in it
   */
MeshNetworkManager.routingTable.put(p.getSenderMac(),
new AllEncompasingP2PClient(p.getSenderMac(), p.getSenderIP(), 
p.getSenderMac(),
MeshNetworkManager.getSelf().getGroupOwnerMac()));
}

activity.runOnUiThread(new Runnable() {

@Override
public void run() {
if (activity.isVisible) {
Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
} else {
MessageActivity.addMessage(name, msg);
}
}
    });
updatePeerList();

AESEncryption.java

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
//import javax.xml.bind.DatatypeConverter;

public class AESEncryption {

public static SecretKey getSecretEncryptionKey() throws Exception{
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(128); // The AES key size in number of bits
    SecretKey secKey = generator.generateKey();
    return secKey;
}

public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
    byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
    return byteCipherText;
}

public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE, secKey);
    byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
    return new String(bytePlainText);
}

public static SecretKey thisKey() throws Exception{

    SecretKey secKey = AESEncryption.getSecretEncryptionKey();

    return secKey;
}

}

in this class where i code the decrypted message. but when i run the code, the messages not decrypt and show ciphert text instead.if someone can correct me, its will great.

Zamri94
  • 15
  • 3
  • 2
    1. Where is the code for `AESEncryption.encryptText` and `AESEncryption.decryptText`. 2. Potential reasons for the failure include incorrect key and/or IV length, incorrect encodings. 3. Provide a [mcve] example complete with code, data, keys, etc and results from you attempts at debugging. 4. Add information on what you have done so far to debug and the results. – zaph Dec 04 '17 at 23:01
  • 1
    Zaph is absolutely correct. Additionally, look here: [android encryption/decryption with AES](https://stackoverflow.com/questions/6788018/android-encryption-decryption-with-aes) – paulsm4 Dec 04 '17 at 23:11
  • sorry about that, i already edit it back – Zamri94 Dec 04 '17 at 23:23
  • 2
    I see you are using ECB mode: Do not use ECB mode in new work and update legacy work ASAP, it is not secure, see [ECB mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29), scroll down to the Penguin. Instead use CBC mode with a random IV, just prefix the encrypted data with the IV for use in decryption, it does not need to be secret. – zaph Dec 05 '17 at 03:50

1 Answers1

2

The same key must be used for both encryption and decryption for the same message.

It seems the same key is not being used for both encryption and decryption, both methods call SecretKey thisKey() which seems to generate a random key.

On encryption call SecretKey thisKey(), use it for encryption and save the key to use on decryption. On decryption do not call SecretKey thisKey(), use the key created for encryption.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • 1
    it mean that i only need to create 1 key, then pass the key to receiver right. now i get the idea how it work. – Zamri94 Dec 07 '17 at 12:21