김동준

DLPonUSB initial commit

/DLPonUSB/DLPonUSB.iml
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_14" project-jdk-name="14" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/DLPonUSB.iml" filepath="$PROJECT_DIR$/DLPonUSB.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
\ No newline at end of file
MIT License
Copyright (c) 2019 stephan-t
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Cryptor
## Description
Command-line tool for encrypting/decrypting files with the AES-256 block cipher operating in CBC mode. The secret key is derived from a user-provided password using the PBKDF2 key derivation function. The SHA-512 cryptographic hash function is used to generate an HMAC for password and data integrity verification.
## Usage
With command-line arguments:
`java cryptor.Main -encrypt plaintext ciphertext password`
`java cryptor.Main -decrypt ciphertext plaintext password`
With command prompts:
`java cryptor.Main`
package cryptor;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Arrays;
/**
* Provides authenticated encryption/decryption using an MAC and secret key.
* An Encrypt-then-MAC (EtM) approach is used, where the plaintext is encrypted
* and an MAC is generated from the resulting ciphertext.
*/
class Authenticator {
private static final String MAC_ALGORITHM = "HmacSHA512";
private static final int MAC_SIZE = 64;
/**
* Generates a MAC based on a given secret key and ciphertext.
* @param key the secret key used in the hash algorithm.
* @param bytes the ciphertext bytes used to generate a MAC.
* @return the generated MAC bytes.
*/
static byte[] generateMac(SecretKey key, byte[] bytes)
throws GeneralSecurityException {
// Generate and prepend a MAC for authentication
Mac mac = Mac.getInstance(MAC_ALGORITHM);
mac.init(key);
return mac.doFinal(bytes);
}
/**
* Retrieves a prepended MAC from an input stream of bytes.
* @param in the input stream to retrieve the MAC from.
* @return the prepended MAC bytes.
*/
static byte[] getMac(InputStream in) throws IOException {
return in.readNBytes(MAC_SIZE);
}
/**
*
* @param prepended the prepended MAC bytes from the ciphertext.
* @param generated the generated MAC bytes from the ciphertext.
* @return <code>true</code> if both MACs match; throws exception otherwise.
* @throws GeneralSecurityException if there is a mismatch between the
* prepended and generated MACs.
*/
static boolean verifyMAC(byte[] prepended, byte[] generated)
throws GeneralSecurityException {
if (Arrays.equals(prepended, generated)) {
return true;
} else {
throw new GeneralSecurityException("Password is invalid" +
" and/or data integrity check failed");
}
}
}
package cryptor;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
/**
* Encrypts or decrypts a file using AES and a PBKDF2 derived cipher key.
*/
class Cryptor {
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final int IV_SIZE = 16;
/**
* Encrypts an input file with password and writes to an output file
* @param inFile the input plaintext file.
* @param outFile the output ciphertext file.
* @param password the password used for encryption.
*/
static void encrypt(String inFile, String outFile, char[] password)
throws IOException, GeneralSecurityException {
try (InputStream in = new FileInputStream(inFile);
OutputStream out = new FileOutputStream(outFile)) {
// Derive key from password
SecretKey key = KeyGenerator.deriveKey(password, out);
// Generate initialization vector and prepend to output
SecureRandom random = new SecureRandom();
byte[] ivBytes = new byte[IV_SIZE];
random.nextBytes(ivBytes);
IvParameterSpec iv = new IvParameterSpec(ivBytes);
out.write(ivBytes);
// Encrypt file
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] outBytes = cipher.doFinal(in.readAllBytes());
// Generate and prepend a MAC
byte[] macBytes = Authenticator.generateMac(key, outBytes);
out.write(macBytes);
out.write(outBytes);
}
}
/**
* Decrypts an input file with password and writes to an output file
* @param fileIn the input ciphertext file.
* @param fileOut the output plaintext file.
* @param password the password used for decryption.
*/
static void decrypt(String fileIn, String fileOut, char[] password)
throws IOException, GeneralSecurityException {
try (InputStream in = new FileInputStream(fileIn)) {
// Derive key from password
SecretKey key = KeyGenerator.deriveKey(password, in);
// Get prepended initialization vector from input
byte[] ivBytes = in.readNBytes(IV_SIZE);
IvParameterSpec iv = new IvParameterSpec(ivBytes);
// Get prepended MAC from input
byte[] tagMacBytes = Authenticator.getMac(in);
// Generate MAC from ciphertext and compare with prepended MAC
byte[] inBytes = in.readAllBytes();
byte[] genMacBytes = Authenticator.generateMac(key, inBytes);
// Decrypt file if both MACs match
if (Authenticator.verifyMAC(tagMacBytes, genMacBytes)) {
try (OutputStream out = new FileOutputStream(fileOut)) {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] outBytes = cipher.doFinal(inBytes);
out.write(outBytes);
}
}
}
}
}
\ No newline at end of file
package cryptor;
import javax.swing.*;
import javax.swing.filechooser.FileView;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Date;
class DecryptWindow extends Frame {
Label lpwd;
Label lmod;
TextField tfId;
TextField tfPwd;
TextField tfMod;
Button ok;
String fileIn;
String fileName;
String userId;
String userPW;
DecryptWindow(String title, String ID, String PW){
//Frame(String title)을 호출한다.
super(title);
userId = ID;
userPW = PW;
//Label의 text정렬을 오른쪽으로
String folderDir = ".\\" + userId + "\\Encrypted";
final File dirToLock = new File(folderDir);
JFileChooser jfc = new JFileChooser(dirToLock);
jfc.setFileView(new FileView() {
@Override
public Boolean isTraversable(File f) {
return dirToLock.equals(f);
}
});
jfc.showOpenDialog(null);
fileIn = jfc.getSelectedFile().getAbsolutePath();
fileName = jfc.getSelectedFile().getName();
lpwd = new Label("Enter password: ",Label.RIGHT);
lmod = new Label("열람 목적: ",Label.RIGHT);
//약 10개의 글자를 입력할 수 있는 TextField 생성.
tfPwd = new TextField(10);
tfMod = new TextField(10);
//입력한 값 대신 '*'이 보이게 한다.
ok = new Button("OK");
//OK버튼과 TextField에 이벤트처리를 위한 Listener를 추가해준다.
tfPwd.addActionListener(new EventHandler());
tfMod.addActionListener(new EventHandler());
ok.addActionListener(new EventHandler());
//LayoutManager를 FlowLayout으로
setLayout(new FlowLayout());
//생성한 component들을 Frame에 포함시킨다.
add(lpwd);
add(tfPwd);
add(lmod);
add(tfMod);
add(ok);
setSize(450,65);
//화면이 보이게 한다.
setVisible(true);
}
public static void main(String args[]){
DecryptWindow f = new DecryptWindow("Login", "user1", "12345678");
}
class EventHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//tfId에 입력되어있는 text를 얻어온다.
dispose();
String passwd = userId + ' ' + tfPwd.getText();
char[] password = passwd.toCharArray();
String passwd2 = userId + ' ' + userPW;
char[] password2 = passwd2.toCharArray();
String modeIn = tfMod.getText();
String dir = ".\\" + userId + "\\logs\\" + fileName + ".txt";
File file = new File(dir);
file.getParentFile().mkdir();
try {
file.createNewFile();
} catch (IOException ioException) {
ioException.printStackTrace();
}
dir = ".\\" + userId + "\\Decrypted\\" + fileName;
file = new File(dir);
file.getParentFile().mkdir();
try {
Cryptor.decrypt(fileIn, dir, password);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (GeneralSecurityException generalSecurityException) {
generalSecurityException.printStackTrace();
}
dir = ".\\" + userId + "\\logs\\" + fileName + ".txt";
String dir2 = ".\\" + userId + "\\logs\\" + fileName + ".log";
try {
Cryptor.decrypt(dir2, dir, password2);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (GeneralSecurityException generalSecurityException) {
generalSecurityException.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dir,true);
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}
SimpleDateFormat format1 = new SimpleDateFormat( "yyyy-MM-dd HH:mm");
Date time = new Date();
String time1 = format1.format(time);
String toWrite = "열람\t" + time1 + '\t' + modeIn + '\n';
byte[] b = toWrite.getBytes();
try {
fos.write(b);
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
fos.flush();
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
fos.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
Cryptor.encrypt(dir, dir2, password2);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (GeneralSecurityException generalSecurityException) {
generalSecurityException.printStackTrace();
}
file = new File(dir);
file.delete();
String folderDir = ".\\" + userId + "\\Decrypted";
final File dirToLock = new File(folderDir);
JFileChooser jfc = new JFileChooser(dirToLock);
jfc.setFileView(new FileView() {
@Override
public Boolean isTraversable(File f) {
return dirToLock.equals(f);
}
});
jfc.showOpenDialog(null);
fileIn = jfc.getSelectedFile().getAbsolutePath();
file = new File(fileIn);
try {
Desktop.getDesktop().open(file);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
\ No newline at end of file
package cryptor;
import javax.swing.*;
import javax.swing.filechooser.FileView;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
class DeleteEncypted extends Frame {
String fileIn;
String fileName;
String userId;
String userPW;
DeleteEncypted(String title, String ID, String PW){
//Frame(String title)을 호출한다.
super(title);
userId = ID;
userPW = PW;
//Label의 text정렬을 오른쪽으로
String folderDir = ".\\" + userId + "\\Encrypted";
final File dirToLock = new File(folderDir);
JFileChooser jfc = new JFileChooser(dirToLock);
jfc.setFileView(new FileView() {
@Override
public Boolean isTraversable(File f) {
return dirToLock.equals(f);
}
});
jfc.showOpenDialog(null);
fileIn = jfc.getSelectedFile().getAbsolutePath();
File file = new File(fileIn);
if(file.exists())
{
file.deleteOnExit();
}
}
public static void main(String args[]){
DeleteEncypted f = new DeleteEncypted("Login", "user1", "12345678");
}
class EventHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
dispose();
}
}
}
\ No newline at end of file
package cryptor;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Date;
class EncryptWindow extends Frame {
Label lid;
Label lpwd;
Label lmod;
TextField tfId;
TextField tfPwd;
TextField tfMod;
Button ok;
String fileIn;
String fileName;
String userId;
String userPW;
EncryptWindow(String title, String ID, String PW){
//Frame(String title)을 호출한다.
super(title);
userId = ID;
userPW = PW;
//Label의 text정렬을 오른쪽으로
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
fileIn = jfc.getSelectedFile().getAbsolutePath();
fileName = jfc.getSelectedFile().getName();
lpwd = new Label("Enter password: ",Label.RIGHT);
lmod = new Label("사용 목적: ",Label.RIGHT);
//약 10개의 글자를 입력할 수 있는 TextField 생성.
tfPwd = new TextField(10);
tfMod = new TextField(10);
//입력한 값 대신 '*'이 보이게 한다.
ok = new Button("OK");
//OK버튼과 TextField에 이벤트처리를 위한 Listener를 추가해준다.
tfPwd.addActionListener(new EventHandler());
tfMod.addActionListener(new EventHandler());
ok.addActionListener(new EventHandler());
//LayoutManager를 FlowLayout으로
setLayout(new FlowLayout());
//생성한 component들을 Frame에 포함시킨다.
add(lpwd);
add(tfPwd);
add(lmod);
add(tfMod);
add(ok);
setSize(450,65);
//화면이 보이게 한다.
setVisible(true);
}
public static void main(String args[]){
EncryptWindow f = new EncryptWindow("Login", "user1", "12345678");
}
class EventHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
dispose();
String passwd = userId + ' ' + tfPwd.getText();
char[] password = passwd.toCharArray();
String passwd2 = userId + ' ' + userPW;
char[] password2 = passwd2.toCharArray();
String modeIn = tfMod.getText();
String dir = ".\\" + userId + "\\logs\\" + fileName + ".txt";
String dir2 = ".\\" + userId + "\\logs\\" + fileName + ".log";
File f = new File(dir2);
if(f.exists())
{
try {
Cryptor.decrypt(dir2, dir, password2);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (GeneralSecurityException generalSecurityException) {
generalSecurityException.printStackTrace();
}
}
File file = new File(dir);
file.getParentFile().getParentFile().mkdir();
file.getParentFile().mkdir();
try {
file.createNewFile();
} catch (IOException ioException) {
ioException.printStackTrace();
}
dir = ".\\" + userId + "\\Encrypted\\" + fileName;
file = new File(dir);
file.getParentFile().mkdir();
try {
Cryptor.encrypt(fileIn, dir, password);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (GeneralSecurityException generalSecurityException) {
generalSecurityException.printStackTrace();
}
dir = ".\\" + userId + "\\logs\\" + fileName + ".txt";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dir,true);
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}
SimpleDateFormat format1 = new SimpleDateFormat( "yyyy-MM-dd HH:mm");
Date time = new Date();
String time1 = format1.format(time);
String toWrite = "등록\t" + time1 + '\t' + modeIn + '\n';
byte[] b = toWrite.getBytes();
try {
fos.write(b);
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
fos.flush();
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
fos.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
Cryptor.encrypt(dir, dir2, password2);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (GeneralSecurityException generalSecurityException) {
generalSecurityException.printStackTrace();
}
file = new File(dir);
file.delete();
}
}
}
\ No newline at end of file
package cryptor;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
/**
* Generates a PBKDF2 derived key for use in a cipher or hash algorithm.
*/
class KeyGenerator {
private static final String KEY_ALGORITHM = "PBKDF2WithHmacSHA512";
private static final String CIPHER_ALGORITHM = "AES";
private static final int SALT_SIZE = 16;
private static final int ITERATIONS = 10000;
private static final int KEY_SIZE = 256;
/**
* Derives a key from the provided password using PBKDF2
* @param password the password to derive a key from.
* @param stream the stream used to prepend or retrieve the salt.
* An <code>InputStream</code> is used for decryption, while an
* <code>OutputStream</code> is used for encryption.
* @return the password derived key.
* @throws IOException if the salt has not been fully read.
* @throws GeneralSecurityException if <code>stream</code> is not of type
* <code>InputStream</code> or <code>OutputStream</code>.
*/
static SecretKey deriveKey(char[] password, Object stream)
throws IOException, GeneralSecurityException {
// Add salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_SIZE];
if (stream instanceof OutputStream) {
// Generate salt and prepend to output
random.nextBytes(salt);
((OutputStream) stream).write(salt);
} else if (stream instanceof InputStream) {
// Get prepended salt from input
salt = ((InputStream) stream).readNBytes(SALT_SIZE);
} else {
throw new IllegalArgumentException("Argument stream must be of type" +
" InputStream or OutputStream");
}
// Derive key
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
KeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_SIZE);
SecretKey key = keyFactory.generateSecret(spec);
return new SecretKeySpec(key.getEncoded(), CIPHER_ALGORITHM);
}
}
package cryptor;
import javax.swing.*;
import javax.swing.filechooser.FileView;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Date;
class LogWindow extends Frame {
String fileIn;
String fileName;
String userId;
String userPW;
LogWindow(String title, String ID, String PW){
//Frame(String title)을 호출한다.
super(title);
userId = ID;
userPW = PW;
//Label의 text정렬을 오른쪽으로
String folderDir = ".\\" + userId + "\\logs";
final File dirToLock = new File(folderDir);
JFileChooser jfc = new JFileChooser(dirToLock);
jfc.setFileView(new FileView() {
@Override
public Boolean isTraversable(File f) {
return dirToLock.equals(f);
}
});
jfc.showOpenDialog(null);
fileIn = jfc.getSelectedFile().getAbsolutePath();
fileName = jfc.getSelectedFile().getName();
String passwd2 = userId + ' ' + userPW;
char[] password2 = passwd2.toCharArray();
String dir = fileIn.substring(0, fileIn.lastIndexOf('.')) + ".txt";
File file = new File(dir);
file.getParentFile().mkdir();
try {
file.createNewFile();
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
Cryptor.decrypt(fileIn, dir, password2);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (GeneralSecurityException generalSecurityException) {
generalSecurityException.printStackTrace();
}
try {
if(file.exists())
{
Desktop.getDesktop().open(file);
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
file.deleteOnExit();
}
public static void main(String args[]){
LogWindow f = new LogWindow("Login", "user1", "12345678");
}
class EventHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
dispose();
}
}
}
\ No newline at end of file
package cryptor;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Scanner;
/**
* Main entry point for running the Cryptor program.
*/
public class Main {
/**
* Calls an encryption or decryption method according to command-line arguments.
* If no arguments are given then command prompts will be shown.
* @param args the command-line arguments.<br>
* Arguments for encryption:
* <ol>
* <li>-encrypt</li>
* <li>plaintext filename</li>
* <li>encrypted filename</li>
* <li>password</li>
* </ol>
* Arguments for decryption:
* <ol>
* <li>-decrypt</li>
* <li>encrypted filename</li>
* <li>decrypted filename</li>
* <li>password</li>
* </ol>
*/
public static void main(String[] args)
throws IOException, GeneralSecurityException {
if (args.length > 0) {
String mode = args[0];
String inFile = args[1];
String outFile = args[2];
char[] password = args[3].toCharArray();
if (mode.equals("-encrypt")) {
Cryptor.encrypt(inFile, outFile, password);
} else if (mode.equals("-decrypt")) {
Cryptor.decrypt(inFile, outFile, password);
} else {
throw new GeneralSecurityException("Not a valid cipher mode");
}
} else {
Scanner scan = new Scanner(System.in);
System.out.print("Enter input filename: ");
String fileIn = scan.nextLine();
System.out.print("Enter output filename: ");
String fileOut = scan.nextLine();
System.out.print("Enter password: ");
char[] password = scan.nextLine().toCharArray();
System.out.print("Enter cipher mode [encrypt | decrypt]: ");
String modeIn = scan.nextLine();
if (modeIn.equals("encrypt")) {
Cryptor.encrypt(fileIn, fileOut, password);
} else if (modeIn.equals("decrypt")) {
Cryptor.decrypt(fileIn, fileOut, password);
} else {
throw new GeneralSecurityException("Not a valid cipher mode");
}
}
}
}
package cryptor;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Date;
class MainMenu extends Frame {
Button bRegister;
Button bOpen;
Button bViewLog;
Button bDelete;
MainMenu(String title, String ID, String PW){
//Frame(String title)을 호출한다.
super(title);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
String folderDir = ".\\" + ID + "\\Decrypted";
File folder = new File(folderDir);
deleteDirectory(folder, ID, PW);
dispose();
System.exit(0);
}
});
bRegister = new Button("Register Files");
bOpen = new Button("Open Encrypted Files");
bViewLog = new Button("View Logs");
bDelete = new Button("Delete Encrypted Files");
//OK버튼과 TextField에 이벤트처리를 위한 Listener를 추가해준다.
bRegister.addActionListener(e -> {
EncryptWindow f = new EncryptWindow(title, ID, PW);
});
bOpen.addActionListener(e -> {
DecryptWindow f = new DecryptWindow(title, ID, PW);
});
bViewLog.addActionListener(e -> {
LogWindow f = new LogWindow(title, ID, PW);
});
bDelete.addActionListener(e -> {
DeleteEncypted f = new DeleteEncypted(title, ID, PW);
});
//LayoutManager를 FlowLayout으로
setLayout(new FlowLayout());
//생성한 component들을 Frame에 포함시킨다.
add(bRegister);
add(bOpen);
add(bViewLog);
add(bDelete);
setSize(450,200);
//화면이 보이게 한다.
setVisible(true);
}
public static void main(String args[]){
MainMenu f = new MainMenu("Main", "user1", "12345678");
}
public static boolean deleteDirectory(File path, String userId, String userPW) {
if(!path.exists()) {
return false;
}
File[] files = path.listFiles();
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file, userId, userPW);
} else {
String fileName = file.getName();
String passwd2 = userId + ' ' + userPW;
char[] password2 = passwd2.toCharArray();
String dir = ".\\" + userId + "\\logs\\" + fileName + ".txt";
String dir2 = ".\\" + userId + "\\logs\\" + fileName + ".log";
try {
Cryptor.decrypt(dir2, dir, password2);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (GeneralSecurityException generalSecurityException) {
generalSecurityException.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dir,true);
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}
SimpleDateFormat format1 = new SimpleDateFormat( "yyyy-MM-dd HH:mm");
Date time = new Date();
String time1 = format1.format(time);
String toWrite = "삭제\t" + time1 + '\t' + "사용 완료" + '\n';
byte[] b = toWrite.getBytes();
try {
fos.write(b);
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
fos.flush();
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
fos.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
Cryptor.encrypt(dir, dir2, password2);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (GeneralSecurityException generalSecurityException) {
generalSecurityException.printStackTrace();
}
File temp = new File(dir);
temp.delete();
file.delete();
}
}
return path.delete();
}
}
\ No newline at end of file