Android – base64 InvalidKeyException: Key length not 128/192/256 bits

androidbase64encryption-symmetricexceptionsharedpreferences

I am trying to encrypt editText strings using Base64 wnich will be saved in sharedpreferences but once the strings are encoded and saved my .xml file is blank. I am a novice programmer and very new to encrytion so Im lost and do not know how to properly analyze my code to determine the problem which may be very simple. I have received some suggestion but nothing that clearly shows where the issue is, why its not working, and how to resolve it. I suspect my encryption method but not sure where. This must be a common task for coders who are trying to protect username and password entries. This tutorial was the used for this encryption project Click Here

Here is class for encoding, encrypting, and saving EditText String:

public void onClick(View arg0) {
    user=rName.getText().toString().trim();
    pass=rPwd.getText().toString().trim();

    if(arg0==regBttn){     
       if((user.length()!=0))
        {
          if((pass.length()!=0))
        {

        sp=getSharedPreferences("AccessApp",MODE_WORLD_WRITEABLE);
        Editor myEditor=sp.edit();

        byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };

        try {
             String encryptedUser = encrypt(user, key);  
             myEditor.putString("USERNAME_KEY", encryptedUser); 
        }
     catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
    try {
             String encryptedPass = encrypt(pass, key);  
             myEditor.putString("PASSWORD_KEY", encryptedPass); 

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    myEditor.commit();
    Toast.makeText(this, "Registration is successfull",10000).show();
    i=new Intent(this,AccessApp.class);
    startActivity(i);
    }
    else
     {
      Toast.makeText(this, "Please Enter password", 10000).show();  
     }}

    else{
        Toast.makeText(this,"Please Enter Username",10000).show();
     }
        }

else if(arg0==rtnBttn){
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
     builder.setTitle("Exit");
     builder.setMessage("Do you want to exit");
     builder.setCancelable(false);
     builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {

  public void onClick(DialogInterface dialog, int which) {
  // TODO Auto-generated method stub
  finish();
  }
  });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                arg0.cancel();
            }
        });
    AlertDialog alert=builder.create();
    alert.show();
}
    }

public String encrypt(String toEncrypt, byte key[]) throws Exception {
    SecretKeySpec secret = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    byte[] encryptedBytes = cipher.doFinal(toEncrypt.getBytes());
    String encrypted = Base64.encodeBytes(encryptedBytes);
    return encrypted;

}

}

Logcat:

 11-11 23:41:59.873: W/System.err(11404): java.security.InvalidKeyException: Key length not 128/192/256 bits.
 11-11 23:41:59.873: W/System.err(11404):   at com.android.org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(JCEBlockCipher.java:570)
 11-11 23:41:59.894: W/System.err(11404):   at com.android.org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(JCEBlockCipher.java:617)
 11-11 23:41:59.903: W/System.err(11404):   at javax.crypto.Cipher.init(Cipher.java:519)
 11-11 23:41:59.928: W/System.err(11404):   at javax.crypto.Cipher.init(Cipher.java:479)
 11-11 23:41:59.943: W/System.err(11404):   at com.SharedPreferences.Login.SharedPrefLoginActivity.encrypt(SharedPrefLoginActivity.java:139)
 11-11 23:41:59.953: W/System.err(11404):   at com.SharedPreferences.Login.SharedPrefLoginActivity.onClick(SharedPrefLoginActivity.java:82)
 11-11 23:41:59.953: W/System.err(11404):   at android.view.View.performClick(View.java:3511)
 11-11 23:41:59.953: W/System.err(11404):   at android.view.View$PerformClick.run(View.java:14105)
 11-11 23:41:59.973: W/System.err(11404):   at android.os.Handler.handleCallback(Handler.java:605)
 11-11 23:41:59.973: W/System.err(11404):   at android.os.Handler.dispatchMessage(Handler.java:92)
 11-11 23:42:00.034: W/System.err(11404):   at android.os.Looper.loop(Looper.java:137)
 11-11 23:42:00.034: W/System.err(11404):   at android.app.ActivityThread.main(ActivityThread.java:4424)
 11-11 23:42:00.034: W/System.err(11404):   at java.lang.reflect.Method.invokeNative(Native Method)
 11-11 23:42:00.103: W/System.err(11404):   at java.lang.reflect.Method.invoke(Method.java:511)
 11-11 23:42:00.103: W/System.err(11404):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
 11-11 23:42:00.124: W/System.err(11404):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
 11-11 23:42:00.124: W/System.err(11404):   at dalvik.system.NativeStart.main(Native Method)

Best Answer

You seem to have miscounted your bytes:

byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };

You need a 128bit key (16 bytes), but you've declared 17 bytes here. Reduce the key length by one and I think it should work.

Related Topic