-
-
Save Fullplate/4f2d633728115b3e7112 to your computer and use it in GitHub Desktop.
Binary file encryption and decryption (AES) (Java)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is not working for me...