在Java中處理ZIP文件的加密和解密,可以使用java.util.zip
包中的類和方法
import java.io.*;
import java.util.zip.*;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public static SecretKeySpec generateEncryptionKey(String key) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(key.getBytes());
return new SecretKeySpec(hash, "AES");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void encryptZipFile(String zipFilePath, String outputZipFile, SecretKeySpec key) {
try {
FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputZipFile));
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
zos.putNextEntry();
byte[] buffer = new byte[1024];
int len;
while ((len = zis.read(buffer)) > 0) {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(buffer, 0, len);
zos.write(encryptedBytes);
}
zos.closeEntry();
zis.closeEntry();
}
zis.close();
zos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void decryptZipFile(String zipFilePath, String outputZipFile, SecretKeySpec key) {
try {
FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputZipFile));
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
zos.putNextEntry();
byte[] buffer = new byte[1024];
int len;
while ((len = zis.read(buffer)) > 0) {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(buffer, 0, len);
zos.write(decryptedBytes);
}
zos.closeEntry();
zis.closeEntry();
}
zis.close();
zos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String zipFilePath = "path/to/your/input.zip";
String encryptedZipFile = "path/to/your/encrypted.zip";
String decryptedZipFile = "path/to/your/decrypted.zip";
String key = "yourEncryptionKey16bytes"; // 16 bytes for AES-128, 24 bytes for AES-192, 32 bytes for AES-256
SecretKeySpec keySpec = generateEncryptionKey(key);
// Encrypt the ZIP file
encryptZipFile(zipFilePath, encryptedZipFile, keySpec);
// Decrypt the ZIP file
decryptZipFile(encryptedZipFile, decryptedZipFile, keySpec);
}
請注意,這個示例使用了AES加密算法。你可以根據需要選擇其他加密算法。同時,確保密鑰長度與所選加密算法相匹配。例如,對于AES-128,密鑰長度應為16字節,對于AES-192,密鑰長度應為24字節,對于AES-256,密鑰長度應為32字節。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。