我必须在android中加密和解密文件,加密文件(图像,视频)也可以从其他设备解密。
我在同一设备中加密和解密它工作正常但是当我切换设备用户加密文件解密时它在doFinal()中显示错误
javax.crypto.IllegalBlockSizeException:最后一个块在解密中不完整
是从一个设备加密文件并访问所有其他设备的任何方法,例如 android.and 使用该密码密钥到其他设备,我们访问文件信息。
// 代码
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;
}
下面是 EncryptDecryptUtils 类的代码
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;
}