java - How to properly convert String to byte[] on text encryption/decryption in android? (Errors - WRONG_FINAL_BLOCK_LENGTH and IllegalBlockSizeException) -


hello looking answers in stack overflow. of dont work. please me.

i'd encryption , decryption text in android. id simple can. firstly wrote code in java eclipse. work fine if transfer android studio there couple of errors.

i must transfer bytes[] string because use firebase , not support storing class object bytes[]

i try work this hint, , many others have failure.

generatekey()

private static secretkey generatekey() throws exception     {          secretkey  key = new secretkeyspec(org.apache.commons.codec.binary.hex.decodehex(klucz.tochararray()), "aes");                   return key;     } 

encrypt(msg)

public string encrypt(string messagetext) {     try     {         byte[] data = messagetext.getbytes("utf-8");           ivparameterspec iv = new ivparameterspec(iv_.getbytes("utf-8"));         secretkeyspec key = (secretkeyspec) generatekey();          cipher cipher = cipher.getinstance("aes/cbc/pkcs5padding");         cipher.init(cipher.encrypt_mode, key, iv);           byte[] textbytes = cipher.dofinal(messagetext.getbytes("utf-8"));         string textstring = base64.encodetostring(textbytes, base64.default);          return  textstring;       }     catch (exception ex)     {         ex.printstacktrace();     }      return null; } 

decrypt(msg)

   public string decrypt(string msgtext)     {         try         {             byte[] data = msgtext.getbytes("utf-8");              ivparameterspec iv = new ivparameterspec(iv_.getbytes("utf-8"));             secretkeyspec skeyspec = (secretkeyspec) generatekey();              cipher cipher = cipher.getinstance("aes/cbc/pkcs5padding");             cipher.init(cipher.decrypt_mode, skeyspec, iv);               byte[] original = cipher.dofinal(data);             string textstring = new string(original, "utf-8");             return textstring;           }         catch (exception ex)         {             ex.printstacktrace();         }          return null;     } 

when sth got error:

wrong_final_block_length

when try change simple aes

cipher cipher = cipher.getinstance("aes"); cipher.init(cipher.decrypt_mode, skeyspec); 

i got error:

illegalblocksizeexception:

you have encoded ciphertext in base64 after encryption, have not decoded before decryption

remove in decrypt() code

  byte[] data = msgtext.getbytes("utf-8"); 

and add

byte[] data = base64.decode(msgtext, base64.default); 

note: not use aes in cipher cipher = cipher.getinstance("aes");. use specific mode avoid unexpected results in android


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -