用Java压缩加密文件
无法压缩文件。我正在制作的应用程序允许您向一组文件添加密码,然后使用DES对这些文件进行加密(在更改为AES的过程中),然后将其保存到文件夹中。但是在它们被加密和密码保护之后,如何压缩它们呢?我已经指定了加密从何处开始使其更容易用Java压缩加密文件,java,file,encryption,zip,Java,File,Encryption,Zip,无法压缩文件。我正在制作的应用程序允许您向一组文件添加密码,然后使用DES对这些文件进行加密(在更改为AES的过程中),然后将其保存到文件夹中。但是在它们被加密和密码保护之后,如何压缩它们呢?我已经指定了加密从何处开始使其更容易 package gui; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; imp
package gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.AlgorithmParameters;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class FileTable extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTable table;
private DefaultTableModel tableModel = new DefaultTableModel(new String[] {"File", "Size", "Status" }, 0);
private File dir;
private File temp;
private JPopupMenu popup;
private String key;
private PasswordStorage passwordStorage;
private JFileChooser fileChooser;
private static String salt = "loquetdeliciouslysalty";
private static byte[] IV;
public FileTable() {
// Set Layout Manager
setLayout(new BorderLayout());
// Create Swing Components
table = new JTable();
table.setModel(tableModel);
table.setDropTarget(new TableDnD(table));
table.setShowGrid(false);
table.setFillsViewportHeight(true);
table.getColumnModel().getColumn(0).setPreferredWidth(250);
passwordStorage = new PasswordStorage();
fileChooser = new JFileChooser();
popup = new JPopupMenu();
JMenuItem removeItem = new JMenuItem("Remove");
removeItem.setIcon(new ImageIcon("removeMenu.png"));
popup.add(removeItem);
// Add Components to pane
add(new JScrollPane(table), BorderLayout.CENTER);
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
table.getSelectionModel().setSelectionInterval(row, row);
if(e.getButton() == MouseEvent.BUTTON3) {
popup.show(table, e.getX(), e.getY());
}
}
});
removeItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int row = table.getSelectedRow();
if(row > -1) {
tableModel.removeRow(table.getSelectedRow());
}
}
});
}
public boolean isTableEmpty() {
if(tableModel.getRowCount() == 0) {
return true;
}
else {
return false;
}
}
public void addFile(File file) {
tableModel.addRow(new Object[]{file, file.length() + " kb","Not Processed"});
}
public void removeFile() {
int[] rows = table.getSelectedRows();
for(int i = 0; i < rows.length; i++) {
tableModel.removeRow(rows[i]-i);
}
}
public void clearTable()
{
int rowCount = tableModel.getRowCount();
for(int i = 0; i < rowCount; i++) {
tableModel.removeRow(0);
}
table.removeAll();
}
public void encrypt() {
if(!isTableEmpty()) {
try {
do {
key = JOptionPane.showInputDialog(this,
"Enter password", "Password",
JOptionPane.OK_OPTION|JOptionPane.PLAIN_MESSAGE); // key needs to be at least 8 characters for DES
if(key == null) break;
} while(key.length() < 8);
// If OK and length of password >= 8 encrypt files
if(key != null) {
// Store password
passwordStorage.write(key);
// Custom Folder for encrypted files
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
dir = fileChooser.getSelectedFile();
}
else {
// Default Folder for decrypted files
dir = new File("encrypted");
dir.mkdir();
}
for(int i = 0; i < tableModel.getRowCount(); i++) {
temp = (File) tableModel.getValueAt(i, 0);
FileInputStream fis2 = new FileInputStream(temp);
FileOutputStream fos2 = new FileOutputStream(dir + "\\" + (temp.getName()));
encrypt(key, fis2, fos2);
}
for(int i = 0; i < tableModel.getRowCount(); i++) {
File toDelete = (File) tableModel.getValueAt(i, 0);
toDelete.delete();
}
// Encryption complete message
JOptionPane.showMessageDialog(this, "Files encrypted succesfully!");
// CLEAR LIST
table.removeAll();
clearTable();
}
} catch (Throwable te) { te.printStackTrace(); }
}
}
public void decrypt() {
if(!isTableEmpty()) {
try {
key = JOptionPane.showInputDialog(this,
"Enter password", "Password",
JOptionPane.OK_OPTION|JOptionPane.PLAIN_MESSAGE);
while(!passwordStorage.isPassword(key)) {
key = JOptionPane.showInputDialog(this,
"Enter password", "Wrong Password!",
JOptionPane.OK_OPTION|JOptionPane.ERROR_MESSAGE);
}
// If OK and length of password >= 8 decrypt files
if(key != null) {
// Custom Folder for decrypted files
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
dir = fileChooser.getSelectedFile();
}
else {
// Default Folder for decrypted files
dir = new File("decrypted");
dir.mkdir();
}
for(int i = 0; i < tableModel.getRowCount(); i++) {
temp = (File) tableModel.getValueAt(i, 0);
FileInputStream fis2 = new FileInputStream(temp);
FileOutputStream fos2 = new FileOutputStream(dir + "\\" + (temp.getName()));
decrypt(key, fis2, fos2);
}
for(int i = 0; i < tableModel.getRowCount(); i++) {
File toDelete = (File) tableModel.getValueAt(i, 0);
toDelete.delete();
}
// Encryption complete message
JOptionPane.showMessageDialog(this, "Files decrypted succesfully!");
// CLEAR LIST
table.removeAll();
clearTable();
}
} catch (Throwable te) { te.printStackTrace(); }
}
}
/*************************************************************************************************************
* ENCRYPTION METHODS ***********************************************************************************
*************************************************************************************************************/
public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}
public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
}
public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
char[] kgen = key.toCharArray();
byte[] ksalt = salt.getBytes();
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(kgen, ksalt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey aesKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
/*DESKeySpec dks = new DESKeySpec((salt + key).getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE*/
if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
saveIv(iv);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(getIv()));
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}
public static void saveIv(byte[] iv) {
IV = iv;
}
public static byte[] getIv() {
return IV;
}
public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[1024];
int numBytes;
while ((numBytes = is.read(bytes)) > 0) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}
}
packagegui;
导入java.awt.BorderLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.event.MouseAdapter;
导入java.awt.event.MouseEvent;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.security.AlgorithmParameters;
导入java.security.spec.KeySpec;
导入javax.crypto.Cipher;
导入javax.crypto.cipheriputstream;
导入javax.crypto.CipherOutputStream;
导入javax.crypto.SecretKey;
导入javax.crypto.SecretKeyFactory;
导入javax.crypto.spec.IvParameterSpec;
导入javax.crypto.spec.PBEKeySpec;
导入javax.crypto.spec.SecretKeySpec;
导入javax.swing.ImageIcon;
导入javax.swing.JFileChooser;
导入javax.swing.JMenuItem;
导入javax.swing.JOptionPane;
导入javax.swing.JPanel;
导入javax.swing.jpopmenu;
导入javax.swing.JScrollPane;
导入javax.swing.JTable;
导入javax.swing.table.DefaultTableModel;
公共类FileTable扩展了JPanel{
/**
*
*/
私有静态最终长serialVersionUID=1L;
专用JTable表;
private DefaultTableModel tableModel=新的DefaultTableModel(新字符串[]{“文件”、“大小”、“状态”},0);
私有文件目录;
私有文件温度;
私有JPOppMenu弹出窗口;
私钥;
专用密码存储;密码存储;
私有JFileChooser文件选择器;
私有静态字符串salt=“loquetdeliciouslysalty”;
专用静态字节[]IV;
公共文件表(){
//设置布局管理器
setLayout(新的BorderLayout());
//创建Swing组件
table=新的JTable();
table.setModel(tableModel);
表.setDropTarget(新表DND(表));
表1.setShowGrid(假);
表.setFillsViewPerthweight(真);
table.getColumnModel().getColumn(0).setPreferredWidth(250);
passwordStorage=新的passwordStorage();
fileChooser=newjfilechooser();
popup=new JPopupMenu();
JMenuItem removeItem=新的JMenuItem(“删除”);
removietem.setIcon(新的图像图标(“removeemenu.png”);
弹出。添加(删除项目);
//将组件添加到窗格
添加(新的JScrollPane(表),BorderLayout.CENTER);
表.addMouseListener(新的MouseAdapter(){
公共无效鼠标按下(MouseEvent e){
int row=table.rowAtPoint(如getPoint());
table.getSelectionModel().setSelectionInterval(行,行);
如果(例如getButton()==MouseEvent.BUTTON3){
show(表,e.getX(),e.getY());
}
}
});
removietem.addActionListener(新ActionListener(){
已执行的公共无效操作(操作事件arg0){
int row=table.getSelectedRow();
如果(第>-1行){
tableModel.removeRow(table.getSelectedRow());
}
}
});
}
公共布尔值isTableEmpty(){
if(tableModel.getRowCount()==0){
返回true;
}
否则{
返回false;
}
}
公共无效添加文件(文件文件){
tableModel.addRow(新对象[]{file,file.length()+“kb”,“未处理”});
}
public void removeFile(){
int[]行=table.getSelectedRows();
for(int i=0;i=8,则加密文件
if(key!=null){
//存储密码
密码存储。写入(密钥);
//用于加密文件的自定义文件夹
fileChooser.setFileSelectionMode(仅限JFileChooser.DIRECTORIES_);
if(fileChooser.showsavedilog(this)=JFileChooser.APPROVE\u选项){
dir=fileChooser.getSelectedFile();
}
否则{
//解密文件的默认文件夹
dir=新文件(“加密”);
dir.mkdir();
}
对于(int i=0;i for(int i = 0; i < tableModel.getRowCount(); i++) {
temp = (File) tableModel.getValueAt(i, 0);
FileInputStream fis2 = new FileInputStream(temp);
FileOutputStream fos2 = new FileOutputStream(dir + "\\"
+ (temp.getName()));
encrypt(key, fis2, fos2);
}
// Zip
ZipOutputStream zipOut = ...
zipOut.setMethod(ZipOutputStream.STORED); // No compression.
for(int i = 0; i < tableModel.getRowCount(); i++) {
// Single file
File originalFile = (File) tableModel.getValueAt(i, 0);
FileInputStream originalStream = new FileInputStream(originalFile);
// GZipped single file:
GZipOutputStream gzipOut = ...; ...
// Input of the gzipped thing
InputStream gzipResultIn = ...
// Make a new ZipEntry:
ZipEntry zipEntry = new ZipEntry(originalFile.getName()
+ ".gz.enc");
zipOut.putNextEntry(zipEntry);
encrypt(key, gzipResultIn, zipOut); // Should not close the input
zipOut.closeEntry();
}
zipOut.close();