gpt4 book ai didi

java - 加密 zip

转载 作者:行者123 更新时间:2023-12-01 11:23:31 29 4
gpt4 key购买 nike

我想要加密我生成的 Zip 文件,其中包含一个文件。我想用密码加密。

这是我第一次使用加密。我做了自己的研究,我似乎理解但不清楚它是如何工作的。

任何人都可以帮助我提供一个清晰的示例,以及一种加密的好方法,向我解释以及如何实现它,或者举一个例子。

我们将不胜感激您的帮助。

最佳答案

我像这样使用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);
}

关于java - 加密 zip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31021248/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com