java - BadPaddingException when decrypting using a different Cipher object -


please excuse hackjob! still new @ coding , utilizing lot of sys outs troubleshoot, , first post @ stackoverflow. thank help!

so i've been working on trying encrypt string objects using javax.crypto.cipher api, , have found success, when using same instance of cipher object. however, purposes of project, encrypting text (string) , decrypting text text file, , not accessing same cipher object every time.

i believe issue not converting between byte arrays , strings, since base64 encoder seems have taken care of problem. output of byte arrays identical pre-encoding , post-decoding, should isolate issue during decryption phase. can done decryptpw method can use different cipher instance (with same arguments passed) , not trigger badpaddingexception?

private static string encryptpw(string pw){     byte[] pwbytes = pw.getbytes();     byte[] keybytes = "0123456789abcdef".getbytes();     secretkeyspec keyspec = new secretkeyspec(keybytes, "aes");     try {         cipher ciph = cipher.getinstance("aes/cbc/pkcs5padding");         ciph.init(cipher.encrypt_mode, keyspec);         byte[] encryptedbytes = ciph.dofinal(pwbytes);         pw = base64.getencoder().encodetostring(ciph.dofinal(pwbytes));          (byte b : encryptedbytes){             system.out.print(b);         }         system.out.println();     } catch (exception e){         e.printstacktrace();     }     return pw; }  private static string decryptpw(string pw){     byte[] pwbytes = base64.getdecoder().decode(pw.getbytes());     (byte b : pwbytes){         system.out.print(b);     }     system.out.println();      byte[] keybytes = "0123456789abcdef".getbytes();     secretkeyspec keyspec = new secretkeyspec(keybytes, "aes");     try {         cipher ciph = cipher.getinstance("aes/cbc/pkcs5padding");         ciph.init(cipher.decrypt_mode, keyspec, ciph.getparameters());         pw = new string(ciph.dofinal(pwbytes));         } catch (exception e){         e.printstacktrace();     }     return pw; } 

again, thank you!

as use cbc mode, need save random initialization vector (iv) encryption cipher , provide decryption cipher.

you can encryption cipher after init like:

ciph.init(cipher.encrypt_mode, keyspec); byte[] iv = ciph.getiv(); 

and provide decrypt cipher like:

ciph.init(cipher.decrypt_mode, keyspec, new ivparameterspec(iv)); 

you need come method of saving iv. common way prefix encrypted data iv, it's available when need initialize decrypt cipher. don't need secret.


Comments

Popular posts from this blog

Ansible warning on jinja2 braces on when -

Parsing a protocol message from Go by Java -

html - How to custom Bootstrap grid height? -