I have to encryption and decryption file in android , and the encrypted file (Image ,video ) can decrypted from other device as well.
I encryption and decryption in same device its working fine but when i am switch the device user the encrypted file to decryption its show me error in doFinal()
javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
is any way to encrypt file from one device and access to all other device like password encryption in android.and using that password key to other device we access the file info.
// code
private boolean encrypt() {
try {
String path = Environment.getExternalStorageDirectory() + File.separator + "Download/tools.png";
String pathe = Environment.getExternalStorageDirectory() + File.separator + "Download/tools.png";
byte[] fileData = FileUtils.readFile(path);
byte[] encodedBytes = EncryptDecryptUtils.encode(EncryptDecryptUtils.getInstance(this).getSecretKey(), fileData);
FileUtils.saveFile(encodedBytes, pathe);
return true;
} catch (Exception e) {
Toast.makeText(this, "File Encryption failed.\nException: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
return false;
}
/**
* Decrypt and return the decoded bytes
*
* @return
*/
private byte[] decrypt() {
try {
String pathe = Environment.getExternalStorageDirectory() + File.separator + "Download/tools.png";
byte[] fileData = FileUtils.readFile(pathe);
byte[] decryptedBytes = EncryptDecryptUtils.decode(EncryptDecryptUtils.getInstance(this).getSecretKey(), fileData);
return decryptedBytes;
} catch (Exception e) {
Toast.makeText(this, "File Decryption failed.\nException: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
Below is the code of EncryptDecryptUtils class
public static byte[] encode(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] data = yourKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length, EncoDecode.KEY_SPEC_ALGORITHM);
Cipher cipher = Cipher.getInstance(EncoDecode.CIPHER_ALGORITHM, EncoDecode.PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
return cipher.doFinal(fileData);
}
public static byte[] decode(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] decrypted;
Cipher cipher = Cipher.getInstance(EncoDecode.CIPHER_ALGORITHM, EncoDecode.PROVIDER);
cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
Log.d("value ", "decode() returned: " + cipher.toString());
decrypted = cipher.doFinal(fileData);
Log.d("", "decode() returned: " + decrypted.length);
return decrypted;
}
public SecretKey getSecretKey() {
String encodedKey = "8qkWUsFfdY8yy5lIad4rjw==";
byte[] decodedKey = Base64.decode(encodedKey, Base64.NO_WRAP);
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, EncoDecode.KEY_SPEC_ALGORITHM);
return originalKey;
}