Skip to content

Instantly share code, notes, and snippets.

@Fullplate
Created August 1, 2014 05:42
Show Gist options
  • Save Fullplate/4f2d633728115b3e7112 to your computer and use it in GitHub Desktop.
Save Fullplate/4f2d633728115b3e7112 to your computer and use it in GitHub Desktop.
Binary file encryption and decryption (AES) (Java)
public static void encryptFile(SecretKeySpec key, IvParameterSpec iv, String inputFilePath, String outputFilePath) {
try {
Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, key, iv);
File inFile = new File(inputFilePath);
File outFile = new File(outputFilePath);
Files.touch(outFile);
InputStream is = new FileInputStream(inFile);
OutputStream os = new FileOutputStream(outFile);
CipherOutputStream cos = new CipherOutputStream(os, encryptCipher);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
cos.write(buffer, 0, length);
}
is.close();
cos.flush();
cos.close();
}
catch (Exception e) {
// log exception
}
}
public static void decryptFile(SecretKeySpec key, IvParameterSpec iv, String inputFilePath, String outputFilePath) {
try {
Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
encryptCipher.init(Cipher.DECRYPT_MODE, key, iv);
File inFile = new File(inputFilePath);
File outFile = new File(outputFilePath);
Files.touch(outFile);
InputStream is = new FileInputStream(inFile);
OutputStream os = new FileOutputStream(outFile);
CipherInputStream cis = new CipherInputStream(is, encryptCipher);
byte[] buffer = new byte[1024];
int length;
while ((length = cis.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
cis.close();
os.flush();
os.close();
}
catch (Exception e) {
// log exception
}
}
@Rahulmanikant
Copy link

It is not working for me...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment