encryption - How to encrypt and decrypt file for Android Kitkat and higher? -
i googling , testing solution while , far no success. there problem it. following code "working" (meaning not show error while running) on android kitkat , higher, decrypted files not readable. why?
final static byte[] iv = new byte[16];//added final static int buffer = 102400; final static string encryptiontype = "aes/cfb8/nopadding";//changed different type static void encrypt(string password, file fileinput, file fileoutput) throws exception { ivparameterspec ivparams = new ivparameterspec(iv);//added fileinputstream fis = new fileinputstream(fileinput); fileoutputstream fos = new fileoutputstream(fileoutput); secretkeyspec sks = new secretkeyspec(password.getbytes("utf-8"), encryptiontype); cipher cipher = cipher.getinstance(encryptiontype); //cipher.init(cipher.encrypt_mode, sks);replaced cipher.init(cipher.encrypt_mode, sks, ivparams); cipheroutputstream cos = new cipheroutputstream(fos, cipher); int b; byte[] d = new byte[buffer]; while ((b = fis.read(d)) != -1) { cos.write(d, 0, b); } cos.flush(); cos.close(); fis.close(); } static void decrypt(string password, file fileinput, file fileoutput) throws exception { ivparameterspec ivparams = new ivparameterspec(iv);//added fileinputstream fis = new fileinputstream(fileinput); fileoutputstream fos = new fileoutputstream(fileoutput); secretkeyspec sks = new secretkeyspec(password.getbytes("utf-8"), encryptiontype); cipher cipher = cipher.getinstance(encryptiontype); //cipher.init(cipher.encrypt_mode, sks);replaced cipher.init(cipher.decrypt_mode, sks, ivparams); cipherinputstream cis = new cipherinputstream(fis, cipher); int b; byte[] d = new byte[buffer]; while ((b = cis.read(d)) != -1) { fos.write(d, 0, b); } fos.flush(); fos.close(); cis.close(); }
edit: after changed type "aes/cfb8/nopadding", seems ok, there no error in process, decrypted file not readable.
the problem in decrypt method caused line:
cipher.init(cipher.encrypt_mode, sks);
the mode needs cipher.decrypt_mode
, line should be
cipher.init(cipher.decrypt_mode, sks);
other issues use of long obsolete desede algorithm, lack of iv generation , handling, absence of password-based key derivation algorithm, , lack of mac on ciphertext. correctly using aes gcm mode proper nonce generation , handling, , use of pbkdf2 (which available on android , oracle java) represent significant improvements.
you don't supply iv, 1 generated automatically. must find way transmit iv recipient. typically iv/nonce prepending ciphertext , stripped off recipient in order decrypt data. cipherinputstream/cipheroutputstream not you, must on own.
Comments
Post a Comment