您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中创建加密的ZIP文件,您可以使用Java库中的java.util.zip
和java.security.MessageDigest
pom.xml
文件中:<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
</dependencies>
import org.apache.commons.compress.archivers.zip.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.Deflater;
public class EncryptedZipCreator {
public static void main(String[] args) {
String[] filesToZip = {"file1.txt", "file2.txt"};
String zipFileName = "encrypted.zip";
String password = "your_password";
try {
createEncryptedZip(filesToZip, zipFileName, password);
System.out.println("Encrypted ZIP file created successfully.");
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static void createEncryptedZip(String[] filesToZip, String zipFileName, String password) throws IOException, NoSuchAlgorithmException {
// Create a new ZIP file and write the encrypted content to it
try (FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos)) {
// Generate a SHA-256 hash of the password for encryption key
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8);
byte[] hashedPassword = md.digest(passwordBytes);
// Compress each file and add it to the ZIP archive
for (String filePath : filesToZip) {
File file = new File(filePath);
byte[] fileBytes = Files.readAllBytes(file.toPath());
// Compress the file content
Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
deflater.setInput(fileBytes);
byte[] compressedData = new byte[1024];
int compressedSize;
while ((compressedSize = deflater.deflate(compressedData)) > 0) {
zos.write(compressedData, 0, compressedSize);
}
// Write the encrypted file header
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry();
zos.write(hashedPassword);
zos.closeEntry();
}
}
}
}
这个示例代码将创建一个名为encrypted.zip
的加密ZIP文件,其中包含两个文本文件(file1.txt
和file2.txt
)。请注意,您需要将your_password
替换为您选择的密码。
此代码使用Java内置的Deflater
类来压缩文件内容,并使用SHA-256哈希算法生成密码的加密密钥。然后,它将每个文件的内容写入ZIP存档,并在文件头中存储加密密钥。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。