wisam
wisam

Reputation: 57

Decryption problem using AES/CBC in android

I am working to make a simple application that encrypts and decrypts a string using AES algorithm with CBC, the encryption is working, while the decryption is not working at all and giving null result when I used to set text to the edit text in the xml, so can anyone help me please? below is my code:

public class MainActivity extends AppCompatActivity {

EditText ptext,ctext,dtext;
Button eButton,dButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     ptext =(EditText)findViewById(R.id.editText);
     ctext =(EditText)findViewById(R.id.editText2);
     dtext =(EditText)findViewById(R.id.editText3);

     eButton = (Button)findViewById(R.id.button);
     dButton = (Button)findViewById(R.id.button2);


    KeyGenerator keyGenerator = null;
    try {
        keyGenerator = KeyGenerator.getInstance("AES");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    keyGenerator.init(128);

    // Generate Key
     final SecretKey key = keyGenerator.generateKey();

    // Generating IV.
    final byte[] IV = new byte[16];
    SecureRandom random = new SecureRandom();
    random.nextBytes(IV);

     eButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
           String plaintext = ptext.getText().toString();
             byte[] cipherText = new byte[0];

                 cipherText = encrypt(plaintext.getBytes(),key, IV);


                 ctext.setText(Base64.getEncoder().encodeToString(cipherText));



         }
     });

     dButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {

             String ciphertext=ctext.getText().toString();


             byte[]    cipher = ciphertext.getBytes();



               String  decryptedText = decrypt(cipher,key, IV);

               dtext.setText(decryptedText);



         }
     });
}

public static byte[] encrypt (byte[] plaintext,SecretKey key,byte[] IV )
{
    try {
        //Get Cipher Instance
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        //Create SecretKeySpec
        SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

        //Create IvParameterSpec
        IvParameterSpec ivSpec = new IvParameterSpec(IV);

        //Initialize Cipher for ENCRYPT_MODE
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

        //Perform Encryption
        byte[] cipherText = cipher.doFinal(plaintext);


        return cipherText;
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}

public static String decrypt (byte[] cipherText, SecretKey key,byte[] IV)
{
    //Get Cipher Instance
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");


    //Create SecretKeySpec
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    //Create IvParameterSpec
    IvParameterSpec ivSpec = new IvParameterSpec(IV);

    //Initialize Cipher for DECRYPT_MODE
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

    //Perform Decryption
    byte[] decryptedText = cipher.doFinal(cipherText);



    return new String(decryptedText);
    } catch (Exception e) {
        e.printStackTrace();

    }
    return null;
}

}

Upvotes: 1

Views: 2587

Answers (2)

kelalaka
kelalaka

Reputation: 5636

You used

Base64.getEncoder().encodeToString(cipherText));

after the encryption process but forget to decode it before the decryption.

Base64.getDecoder().decode( )

Remember, always what you have done, reverse it.

Upvotes: 2

EduardoMaia
EduardoMaia

Reputation: 601

The line

byte[] cipher = ciphertext.getBytes();

is the problem. You should use Base64.decodeBase64(encryptedValue) in decrypt since you use Base64.getEncoder().encodeToString on encrypt. You must do that prior to attempting to decrypt though. You must undo the operations in the reverse order of the encrypt method.

Upvotes: 1

Related Questions