I want to encrypt a large video file called largefile.mp4
most efficiently and then decrypt it again, but there it is not working as expected.
actually there is not any error, and the files gets generated. but the new generated file is too small than the main file.
here largefile.mp4
is 100mb but newEncryptedFile.txt
is 107kb and the newDecryptedFile.mp4
is 210 bytes
What is the problem ?
package fileenc;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
public class FileEncrypterDecrypter {
SecretKey key;
Cipher cipher;
public FileEncrypterDecrypter() {
try {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
key = keygen.generateKey();
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
System.out.println(e);
}
}
public boolean fileEncrypt(String plainFile) {
try (BufferedInputStream fis = new BufferedInputStream(new FileInputStream(plainFile))){
cipher.init(Cipher.ENCRYPT_MODE, key);
FileOutputStream fs = new FileOutputStream("newEncryptedFile.txt");
CipherOutputStream out = new CipherOutputStream(fs, cipher);
byte[] byteSize = new byte[1024];
int numberOfBytedRead;
while ( (numberOfBytedRead = fis.read(byteSize)) != -1 ) {
out.write(numberOfBytedRead);
}
fis.close();
out.flush();
out.close();
System.out.println("Encryption done...");
return true;
} catch (IOException | InvalidKeyException e) {
}
return false;
}
public boolean fileDecrypt(String encryptedFile) {
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("newDecryptedFile.mp4"))){
cipher.init(Cipher.DECRYPT_MODE, key);
FileInputStream fis = new FileInputStream(encryptedFile);
CipherInputStream in = new CipherInputStream(fis, cipher);
byte[] byteSize = new byte[1024];
int numberOfBytedRead;
while ( (numberOfBytedRead = in.read(byteSize)) != -1) {
bos.write(numberOfBytedRead);
}
System.out.println("Decryption done...");
bos.flush();
bos.close();
in.close();
return true;
} catch (IOException | InvalidKeyException e) {
}
return false;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
FileEncrypterDecrypter fed = new FileEncrypterDecrypter();
fed.fileEncrypt("largefile.mp4"); // about 100 mb
fed.fileDecrypt("newEncryptedFile.txt");
}
}