Reputation: 234
I want to Encrypt Zip file that I generate, which contains a files inside it. I want to encrypt it with password.
Its my first time to work with Encryption
. I did my own research
, I seem to understand but not clearly on how it works.
Can anyone help with a clear example, and a good way of encrypting
by explain to me and how do I implement it or maybe give an example.
Your help will be appreciated.
Upvotes: 2
Views: 2934
Reputation: 18245
You can try zip4jvm
char[] password = "password".toCharArray();
ZipEntrySettings entrySettings =
ZipEntrySettings.builder()
.encryption(Encryption.AES_256, password)
.build();
ZipSettings settings =
ZipSettings.builder()
.entrySettingsProvider(fileName -> entrySettings)
.build();
Path zip = Paths.get("dest.zip");
Path srcDir = Paths.get("/srcDir");
ZipIt.zip(zip).settings(settings).add(srcDir);
Upvotes: 2
Reputation: 870
I use CipherOutputStream
like this:
public static void encryptAndClose(FileInputStream fis, FileOutputStream fos)
throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
// Length is 16 byte
SecretKeySpec sks = new SecretKeySpec("1234567890123456".getBytes(), "AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream for encoding
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
//wrap output with buffer stream
BufferedOutputStream bos = new BufferedOutputStream(cos);
//wrap input with buffer stream
BufferedInputStream bis = new BufferedInputStream(fis);
// Write bytes
int b;
byte[] d = new byte[8];
while((b = bis.read(d)) != -1) {
bos.write(d, 0, b);
}
// Flush and close streams.
bos.flush();
bos.close();
bis.close();
}
public static void decryptAndClose(FileInputStream fis, FileOutputStream fos)
throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
SecretKeySpec sks = new SecretKeySpec("1234567890123456".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
//wrap input with buffer stream
BufferedInputStream bis = new BufferedInputStream(cis);
//wrap output with buffer stream
BufferedOutputStream bos = new BufferedOutputStream(fos);
int b;
byte[] d = new byte[8];
while((b = bis.read(d)) != -1) {
bos.write(d, 0, b);
}
bos.flush();
bos.close();
bis.close();
}
I use it like this:
File output= new File(outDir, outFilename);
File input= new File(inDir, inFilename);
if (input.exists()) {
FileInputStream inStream = new FileInputStream(input);
FileOutputStream outStream = new FileOutputStream(output);
encryptAndClose(inStream, outStream);
}
Upvotes: 2