Security- decrypting in java "BadPaddingException" -
i'm encrypting strings , writing them text file. in order decrypt content, i'm reading file , print decrypted data. when tested code 1 string value, encrypted , decrypted fine; however, when added more strings encrypt, encryption worked fine decryption gave me exception "javax.crypto.badpaddingexception: given final block not padded "
this code. please help!
// these initialized in main secretkey key = keygenerator.getinstance("des").generatekey(); algorithmparameterspec paramspec = new ivparameterspec(iv); ecipher = cipher.getinstance("des/cbc/pkcs5padding"); dcipher = cipher.getinstance("des/cbc/pkcs5padding"); ecipher.init(cipher.encrypt_mode, key, paramspec); dcipher.init(cipher.decrypt_mode, key, paramspec); // catches .. // take string , file have encrypted strings private static void encrypt(string s, outputstream os) throws illegalblocksizeexception, badpaddingexception { try { byte[] buf = s.getbytes(); byte[] b = ecipher.dofinal(buf); os.write(b); // write new line after writing each encrypted value , avoid overwriting os.write(system.getproperty("line.separator").getbytes()); os.flush(); os.close(); } catch (ioexception e) { system.out.println("i/o error:" + e.getmessage()); } } // take file has of encryptions private static void decrypt(inputstream is) throws illegalblocksizeexception, badpaddingexception { try { byte[] buf = new byte[is.available()]; is.read(buf); byte[] decrypted = dcipher.dofinal(buf); // cause of problem!!!! system.out.println(new string (decrypted)); is.close(); } catch (ioexception e) { system.out.println("i/o error:" + e.getmessage()); }
when encrypting, you're writing encrypted data output file adding newline, when decrypting, seem reading entire contents of file , decrypting it, include newline character attempt decrypt if part of ciphertext, causing padding exception. you're attempting decrypt of separately written strings using single decrypt call, whereas need decrypted individually.
i suggest converting encrypted data base64 before writing output file , appending newline. when decrypting, read line, convert base64 byte[]
, decrypt, repeat each line in input.
Comments
Post a Comment