我想要生成的加密Zip文件,其中包含文件。我想用密码加密它。
我第一次与Encryption
合作。我做了我自己的research
,我似乎理解但不清楚它是如何工作的。
任何人都可以帮助一个明确的例子,并通过向我解释encrypting
的好方法,我该如何实现它,或者举个例子。
我们将不胜感激。
先谢谢
答案 0 :(得分:1)
我像这样使用CipherOutputStream
:
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();
}
我这样用:
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);
}