김동준

DLPonUSB initial commit

1 +/DLPonUSB/DLPonUSB.iml
1 +# Default ignored files
2 +/shelf/
3 +/workspace.xml
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<project version="4">
3 + <component name="ProjectRootManager" version="2" languageLevel="JDK_14" project-jdk-name="14" project-jdk-type="JavaSDK">
4 + <output url="file://$PROJECT_DIR$/out" />
5 + </component>
6 +</project>
...\ No newline at end of file ...\ No newline at end of file
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<project version="4">
3 + <component name="ProjectModuleManager">
4 + <modules>
5 + <module fileurl="file://$PROJECT_DIR$/DLPonUSB.iml" filepath="$PROJECT_DIR$/DLPonUSB.iml" />
6 + </modules>
7 + </component>
8 +</project>
...\ No newline at end of file ...\ No newline at end of file
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<project version="4">
3 + <component name="VcsDirectoryMappings">
4 + <mapping directory="" vcs="Git" />
5 + <mapping directory="$PROJECT_DIR$/.." vcs="Git" />
6 + </component>
7 +</project>
...\ No newline at end of file ...\ No newline at end of file
1 +MIT License
2 +
3 +Copyright (c) 2019 stephan-t
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +SOFTWARE.
1 +# Cryptor
2 +
3 +## Description
4 +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.
5 +
6 +## Usage
7 +With command-line arguments:
8 +
9 +`java cryptor.Main -encrypt plaintext ciphertext password`
10 +
11 +`java cryptor.Main -decrypt ciphertext plaintext password`
12 +
13 +With command prompts:
14 +
15 +`java cryptor.Main`
1 +package cryptor;
2 +
3 +import javax.crypto.Mac;
4 +import javax.crypto.SecretKey;
5 +import java.io.IOException;
6 +import java.io.InputStream;
7 +import java.security.GeneralSecurityException;
8 +import java.util.Arrays;
9 +
10 +/**
11 + * Provides authenticated encryption/decryption using an MAC and secret key.
12 + * An Encrypt-then-MAC (EtM) approach is used, where the plaintext is encrypted
13 + * and an MAC is generated from the resulting ciphertext.
14 + */
15 +class Authenticator {
16 +
17 + private static final String MAC_ALGORITHM = "HmacSHA512";
18 + private static final int MAC_SIZE = 64;
19 +
20 + /**
21 + * Generates a MAC based on a given secret key and ciphertext.
22 + * @param key the secret key used in the hash algorithm.
23 + * @param bytes the ciphertext bytes used to generate a MAC.
24 + * @return the generated MAC bytes.
25 + */
26 + static byte[] generateMac(SecretKey key, byte[] bytes)
27 + throws GeneralSecurityException {
28 + // Generate and prepend a MAC for authentication
29 + Mac mac = Mac.getInstance(MAC_ALGORITHM);
30 + mac.init(key);
31 + return mac.doFinal(bytes);
32 + }
33 +
34 + /**
35 + * Retrieves a prepended MAC from an input stream of bytes.
36 + * @param in the input stream to retrieve the MAC from.
37 + * @return the prepended MAC bytes.
38 + */
39 + static byte[] getMac(InputStream in) throws IOException {
40 + return in.readNBytes(MAC_SIZE);
41 + }
42 +
43 + /**
44 + *
45 + * @param prepended the prepended MAC bytes from the ciphertext.
46 + * @param generated the generated MAC bytes from the ciphertext.
47 + * @return <code>true</code> if both MACs match; throws exception otherwise.
48 + * @throws GeneralSecurityException if there is a mismatch between the
49 + * prepended and generated MACs.
50 + */
51 + static boolean verifyMAC(byte[] prepended, byte[] generated)
52 + throws GeneralSecurityException {
53 + if (Arrays.equals(prepended, generated)) {
54 + return true;
55 + } else {
56 + throw new GeneralSecurityException("Password is invalid" +
57 + " and/or data integrity check failed");
58 + }
59 + }
60 +}
1 +package cryptor;
2 +
3 +import javax.crypto.Cipher;
4 +import javax.crypto.SecretKey;
5 +import javax.crypto.spec.IvParameterSpec;
6 +import java.io.*;
7 +import java.security.GeneralSecurityException;
8 +import java.security.SecureRandom;
9 +
10 +/**
11 + * Encrypts or decrypts a file using AES and a PBKDF2 derived cipher key.
12 + */
13 +class Cryptor {
14 +
15 + private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
16 + private static final int IV_SIZE = 16;
17 +
18 + /**
19 + * Encrypts an input file with password and writes to an output file
20 + * @param inFile the input plaintext file.
21 + * @param outFile the output ciphertext file.
22 + * @param password the password used for encryption.
23 + */
24 + static void encrypt(String inFile, String outFile, char[] password)
25 + throws IOException, GeneralSecurityException {
26 + try (InputStream in = new FileInputStream(inFile);
27 + OutputStream out = new FileOutputStream(outFile)) {
28 + // Derive key from password
29 + SecretKey key = KeyGenerator.deriveKey(password, out);
30 +
31 + // Generate initialization vector and prepend to output
32 + SecureRandom random = new SecureRandom();
33 + byte[] ivBytes = new byte[IV_SIZE];
34 + random.nextBytes(ivBytes);
35 + IvParameterSpec iv = new IvParameterSpec(ivBytes);
36 + out.write(ivBytes);
37 +
38 + // Encrypt file
39 + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
40 + cipher.init(Cipher.ENCRYPT_MODE, key, iv);
41 + byte[] outBytes = cipher.doFinal(in.readAllBytes());
42 +
43 + // Generate and prepend a MAC
44 + byte[] macBytes = Authenticator.generateMac(key, outBytes);
45 + out.write(macBytes);
46 +
47 + out.write(outBytes);
48 + }
49 + }
50 +
51 + /**
52 + * Decrypts an input file with password and writes to an output file
53 + * @param fileIn the input ciphertext file.
54 + * @param fileOut the output plaintext file.
55 + * @param password the password used for decryption.
56 + */
57 + static void decrypt(String fileIn, String fileOut, char[] password)
58 + throws IOException, GeneralSecurityException {
59 + try (InputStream in = new FileInputStream(fileIn)) {
60 + // Derive key from password
61 + SecretKey key = KeyGenerator.deriveKey(password, in);
62 +
63 + // Get prepended initialization vector from input
64 + byte[] ivBytes = in.readNBytes(IV_SIZE);
65 + IvParameterSpec iv = new IvParameterSpec(ivBytes);
66 +
67 + // Get prepended MAC from input
68 + byte[] tagMacBytes = Authenticator.getMac(in);
69 +
70 + // Generate MAC from ciphertext and compare with prepended MAC
71 + byte[] inBytes = in.readAllBytes();
72 + byte[] genMacBytes = Authenticator.generateMac(key, inBytes);
73 +
74 + // Decrypt file if both MACs match
75 + if (Authenticator.verifyMAC(tagMacBytes, genMacBytes)) {
76 + try (OutputStream out = new FileOutputStream(fileOut)) {
77 + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
78 + cipher.init(Cipher.DECRYPT_MODE, key, iv);
79 + byte[] outBytes = cipher.doFinal(inBytes);
80 + out.write(outBytes);
81 + }
82 + }
83 + }
84 + }
85 +}
...\ No newline at end of file ...\ No newline at end of file
1 +package cryptor;
2 +
3 +import javax.swing.*;
4 +import javax.swing.filechooser.FileView;
5 +import java.awt.*;
6 +import java.awt.event.ActionEvent;
7 +import java.awt.event.ActionListener;
8 +import java.io.File;
9 +import java.io.FileNotFoundException;
10 +import java.io.FileOutputStream;
11 +import java.io.IOException;
12 +import java.security.GeneralSecurityException;
13 +import java.text.SimpleDateFormat;
14 +import java.util.Date;
15 +
16 +class DecryptWindow extends Frame {
17 + Label lpwd;
18 +
19 + Label lmod;
20 +
21 + TextField tfId;
22 +
23 + TextField tfPwd;
24 +
25 + TextField tfMod;
26 +
27 + Button ok;
28 +
29 + String fileIn;
30 +
31 + String fileName;
32 +
33 + String userId;
34 +
35 + String userPW;
36 +
37 +
38 + DecryptWindow(String title, String ID, String PW){
39 +
40 + //Frame(String title)을 호출한다.
41 +
42 + super(title);
43 +
44 + userId = ID;
45 + userPW = PW;
46 +
47 + //Label의 text정렬을 오른쪽으로
48 + String folderDir = ".\\" + userId + "\\Encrypted";
49 +
50 + final File dirToLock = new File(folderDir);
51 + JFileChooser jfc = new JFileChooser(dirToLock);
52 + jfc.setFileView(new FileView() {
53 + @Override
54 + public Boolean isTraversable(File f) {
55 + return dirToLock.equals(f);
56 + }
57 + });
58 +
59 + jfc.showOpenDialog(null);
60 + fileIn = jfc.getSelectedFile().getAbsolutePath();
61 + fileName = jfc.getSelectedFile().getName();
62 +
63 + lpwd = new Label("Enter password: ",Label.RIGHT);
64 +
65 + lmod = new Label("열람 목적: ",Label.RIGHT);
66 +
67 +
68 + //약 10개의 글자를 입력할 수 있는 TextField 생성.
69 +
70 + tfPwd = new TextField(10);
71 +
72 + tfMod = new TextField(10);
73 + //입력한 값 대신 '*'이 보이게 한다.
74 +
75 +
76 +
77 + ok = new Button("OK");
78 +
79 + //OK버튼과 TextField에 이벤트처리를 위한 Listener를 추가해준다.
80 +
81 + tfPwd.addActionListener(new EventHandler());
82 +
83 + tfMod.addActionListener(new EventHandler());
84 +
85 + ok.addActionListener(new EventHandler());
86 +
87 +
88 +
89 + //LayoutManager를 FlowLayout으로
90 +
91 + setLayout(new FlowLayout());
92 +
93 + //생성한 component들을 Frame에 포함시킨다.
94 +
95 + add(lpwd);
96 +
97 + add(tfPwd);
98 +
99 + add(lmod);
100 +
101 + add(tfMod);
102 +
103 + add(ok);
104 +
105 + setSize(450,65);
106 +
107 + //화면이 보이게 한다.
108 +
109 + setVisible(true);
110 +
111 + }
112 +
113 + public static void main(String args[]){
114 +
115 + DecryptWindow f = new DecryptWindow("Login", "user1", "12345678");
116 +
117 + }
118 +
119 +
120 +
121 + class EventHandler implements ActionListener{
122 +
123 + public void actionPerformed(ActionEvent e){
124 +
125 + //tfId에 입력되어있는 text를 얻어온다.
126 +
127 + dispose();
128 +
129 + String passwd = userId + ' ' + tfPwd.getText();
130 + char[] password = passwd.toCharArray();
131 + String passwd2 = userId + ' ' + userPW;
132 + char[] password2 = passwd2.toCharArray();
133 +
134 + String modeIn = tfMod.getText();
135 +
136 + String dir = ".\\" + userId + "\\logs\\" + fileName + ".txt";
137 + File file = new File(dir);
138 + file.getParentFile().mkdir();
139 + try {
140 + file.createNewFile();
141 + } catch (IOException ioException) {
142 + ioException.printStackTrace();
143 + }
144 +
145 + dir = ".\\" + userId + "\\Decrypted\\" + fileName;
146 + file = new File(dir);
147 + file.getParentFile().mkdir();
148 +
149 + try {
150 + Cryptor.decrypt(fileIn, dir, password);
151 + } catch (IOException ioException) {
152 + ioException.printStackTrace();
153 + } catch (GeneralSecurityException generalSecurityException) {
154 + generalSecurityException.printStackTrace();
155 + }
156 +
157 + dir = ".\\" + userId + "\\logs\\" + fileName + ".txt";
158 + String dir2 = ".\\" + userId + "\\logs\\" + fileName + ".log";
159 + try {
160 + Cryptor.decrypt(dir2, dir, password2);
161 + } catch (IOException ioException) {
162 + ioException.printStackTrace();
163 + } catch (GeneralSecurityException generalSecurityException) {
164 + generalSecurityException.printStackTrace();
165 + }
166 +
167 + FileOutputStream fos = null;
168 + try {
169 + fos = new FileOutputStream(dir,true);
170 + } catch (FileNotFoundException fileNotFoundException) {
171 + fileNotFoundException.printStackTrace();
172 + }
173 + SimpleDateFormat format1 = new SimpleDateFormat( "yyyy-MM-dd HH:mm");
174 +
175 + Date time = new Date();
176 +
177 + String time1 = format1.format(time);
178 + String toWrite = "열람\t" + time1 + '\t' + modeIn + '\n';
179 + byte[] b = toWrite.getBytes();
180 + try {
181 + fos.write(b);
182 + } catch (IOException ioException) {
183 + ioException.printStackTrace();
184 + }
185 + try {
186 + fos.flush();
187 + } catch (IOException ioException) {
188 + ioException.printStackTrace();
189 + }
190 + try {
191 + fos.close();
192 + } catch (IOException ioException) {
193 + ioException.printStackTrace();
194 + }
195 +
196 + try {
197 + Cryptor.encrypt(dir, dir2, password2);
198 + } catch (IOException ioException) {
199 + ioException.printStackTrace();
200 + } catch (GeneralSecurityException generalSecurityException) {
201 + generalSecurityException.printStackTrace();
202 + }
203 +
204 + file = new File(dir);
205 + file.delete();
206 +
207 + String folderDir = ".\\" + userId + "\\Decrypted";
208 +
209 + final File dirToLock = new File(folderDir);
210 + JFileChooser jfc = new JFileChooser(dirToLock);
211 + jfc.setFileView(new FileView() {
212 + @Override
213 + public Boolean isTraversable(File f) {
214 + return dirToLock.equals(f);
215 + }
216 + });
217 +
218 + jfc.showOpenDialog(null);
219 + fileIn = jfc.getSelectedFile().getAbsolutePath();
220 + file = new File(fileIn);
221 +
222 + try {
223 + Desktop.getDesktop().open(file);
224 + } catch (IOException ioException) {
225 + ioException.printStackTrace();
226 + }
227 + }
228 +
229 + }
230 +
231 +}
...\ No newline at end of file ...\ No newline at end of file
1 +package cryptor;
2 +
3 +import javax.swing.*;
4 +import javax.swing.filechooser.FileView;
5 +import java.awt.*;
6 +import java.awt.event.ActionEvent;
7 +import java.awt.event.ActionListener;
8 +import java.io.File;
9 +import java.io.IOException;
10 +import java.security.GeneralSecurityException;
11 +
12 +class DeleteEncypted extends Frame {
13 +
14 + String fileIn;
15 +
16 + String fileName;
17 +
18 + String userId;
19 +
20 + String userPW;
21 +
22 +
23 + DeleteEncypted(String title, String ID, String PW){
24 +
25 + //Frame(String title)을 호출한다.
26 +
27 + super(title);
28 +
29 + userId = ID;
30 + userPW = PW;
31 +
32 + //Label의 text정렬을 오른쪽으로
33 + String folderDir = ".\\" + userId + "\\Encrypted";
34 +
35 + final File dirToLock = new File(folderDir);
36 + JFileChooser jfc = new JFileChooser(dirToLock);
37 + jfc.setFileView(new FileView() {
38 + @Override
39 + public Boolean isTraversable(File f) {
40 + return dirToLock.equals(f);
41 + }
42 + });
43 +
44 + jfc.showOpenDialog(null);
45 + fileIn = jfc.getSelectedFile().getAbsolutePath();
46 +
47 + File file = new File(fileIn);
48 +
49 + if(file.exists())
50 + {
51 + file.deleteOnExit();
52 + }
53 + }
54 +
55 + public static void main(String args[]){
56 +
57 + DeleteEncypted f = new DeleteEncypted("Login", "user1", "12345678");
58 +
59 + }
60 +
61 +
62 +
63 + class EventHandler implements ActionListener{
64 +
65 + public void actionPerformed(ActionEvent e){
66 + dispose();
67 + }
68 +
69 + }
70 +
71 +}
...\ No newline at end of file ...\ No newline at end of file
1 +package cryptor;
2 +
3 +import javax.swing.*;
4 +import java.awt.*;
5 +import java.awt.event.*;
6 +import java.io.*;
7 +import java.security.GeneralSecurityException;
8 +import java.text.SimpleDateFormat;
9 +import java.util.Date;
10 +
11 +class EncryptWindow extends Frame {
12 +
13 + Label lid;
14 +
15 + Label lpwd;
16 +
17 + Label lmod;
18 +
19 + TextField tfId;
20 +
21 + TextField tfPwd;
22 +
23 + TextField tfMod;
24 +
25 + Button ok;
26 +
27 + String fileIn;
28 +
29 + String fileName;
30 +
31 + String userId;
32 +
33 + String userPW;
34 +
35 +
36 + EncryptWindow(String title, String ID, String PW){
37 +
38 + //Frame(String title)을 호출한다.
39 +
40 + super(title);
41 +
42 + userId = ID;
43 + userPW = PW;
44 +
45 + //Label의 text정렬을 오른쪽으로
46 + JFileChooser jfc = new JFileChooser();
47 +
48 + jfc.showOpenDialog(null);
49 + fileIn = jfc.getSelectedFile().getAbsolutePath();
50 + fileName = jfc.getSelectedFile().getName();
51 +
52 + lpwd = new Label("Enter password: ",Label.RIGHT);
53 +
54 + lmod = new Label("사용 목적: ",Label.RIGHT);
55 +
56 +
57 + //약 10개의 글자를 입력할 수 있는 TextField 생성.
58 +
59 + tfPwd = new TextField(10);
60 +
61 + tfMod = new TextField(10);
62 + //입력한 값 대신 '*'이 보이게 한다.
63 +
64 +
65 +
66 + ok = new Button("OK");
67 +
68 + //OK버튼과 TextField에 이벤트처리를 위한 Listener를 추가해준다.
69 +
70 + tfPwd.addActionListener(new EventHandler());
71 +
72 + tfMod.addActionListener(new EventHandler());
73 +
74 + ok.addActionListener(new EventHandler());
75 +
76 +
77 +
78 + //LayoutManager를 FlowLayout으로
79 +
80 + setLayout(new FlowLayout());
81 +
82 + //생성한 component들을 Frame에 포함시킨다.
83 + add(lpwd);
84 +
85 + add(tfPwd);
86 +
87 + add(lmod);
88 +
89 + add(tfMod);
90 +
91 + add(ok);
92 +
93 + setSize(450,65);
94 +
95 + //화면이 보이게 한다.
96 +
97 + setVisible(true);
98 +
99 + }
100 +
101 + public static void main(String args[]){
102 +
103 + EncryptWindow f = new EncryptWindow("Login", "user1", "12345678");
104 +
105 + }
106 +
107 +
108 +
109 + class EventHandler implements ActionListener{
110 +
111 + public void actionPerformed(ActionEvent e){
112 +
113 + dispose();
114 +
115 + String passwd = userId + ' ' + tfPwd.getText();
116 + char[] password = passwd.toCharArray();
117 + String passwd2 = userId + ' ' + userPW;
118 + char[] password2 = passwd2.toCharArray();
119 +
120 + String modeIn = tfMod.getText();
121 +
122 + String dir = ".\\" + userId + "\\logs\\" + fileName + ".txt";
123 + String dir2 = ".\\" + userId + "\\logs\\" + fileName + ".log";
124 + File f = new File(dir2);
125 + if(f.exists())
126 + {
127 + try {
128 + Cryptor.decrypt(dir2, dir, password2);
129 + } catch (IOException ioException) {
130 + ioException.printStackTrace();
131 + } catch (GeneralSecurityException generalSecurityException) {
132 + generalSecurityException.printStackTrace();
133 + }
134 + }
135 +
136 + File file = new File(dir);
137 + file.getParentFile().getParentFile().mkdir();
138 + file.getParentFile().mkdir();
139 + try {
140 + file.createNewFile();
141 + } catch (IOException ioException) {
142 + ioException.printStackTrace();
143 + }
144 +
145 + dir = ".\\" + userId + "\\Encrypted\\" + fileName;
146 + file = new File(dir);
147 + file.getParentFile().mkdir();
148 +
149 + try {
150 + Cryptor.encrypt(fileIn, dir, password);
151 + } catch (IOException ioException) {
152 + ioException.printStackTrace();
153 + } catch (GeneralSecurityException generalSecurityException) {
154 + generalSecurityException.printStackTrace();
155 + }
156 +
157 + dir = ".\\" + userId + "\\logs\\" + fileName + ".txt";
158 + FileOutputStream fos = null;
159 + try {
160 + fos = new FileOutputStream(dir,true);
161 + } catch (FileNotFoundException fileNotFoundException) {
162 + fileNotFoundException.printStackTrace();
163 + }
164 + SimpleDateFormat format1 = new SimpleDateFormat( "yyyy-MM-dd HH:mm");
165 +
166 + Date time = new Date();
167 +
168 + String time1 = format1.format(time);
169 + String toWrite = "등록\t" + time1 + '\t' + modeIn + '\n';
170 + byte[] b = toWrite.getBytes();
171 + try {
172 + fos.write(b);
173 + } catch (IOException ioException) {
174 + ioException.printStackTrace();
175 + }
176 + try {
177 + fos.flush();
178 + } catch (IOException ioException) {
179 + ioException.printStackTrace();
180 + }
181 + try {
182 + fos.close();
183 + } catch (IOException ioException) {
184 + ioException.printStackTrace();
185 + }
186 +
187 + try {
188 + Cryptor.encrypt(dir, dir2, password2);
189 + } catch (IOException ioException) {
190 + ioException.printStackTrace();
191 + } catch (GeneralSecurityException generalSecurityException) {
192 + generalSecurityException.printStackTrace();
193 + }
194 +
195 + file = new File(dir);
196 + file.delete();
197 + }
198 + }
199 +
200 +}
...\ No newline at end of file ...\ No newline at end of file
1 +package cryptor;
2 +
3 +import javax.crypto.SecretKey;
4 +import javax.crypto.SecretKeyFactory;
5 +import javax.crypto.spec.PBEKeySpec;
6 +import javax.crypto.spec.SecretKeySpec;
7 +import java.io.IOException;
8 +import java.io.InputStream;
9 +import java.io.OutputStream;
10 +import java.security.GeneralSecurityException;
11 +import java.security.SecureRandom;
12 +import java.security.spec.KeySpec;
13 +
14 +/**
15 + * Generates a PBKDF2 derived key for use in a cipher or hash algorithm.
16 + */
17 +class KeyGenerator {
18 +
19 + private static final String KEY_ALGORITHM = "PBKDF2WithHmacSHA512";
20 + private static final String CIPHER_ALGORITHM = "AES";
21 + private static final int SALT_SIZE = 16;
22 + private static final int ITERATIONS = 10000;
23 + private static final int KEY_SIZE = 256;
24 +
25 + /**
26 + * Derives a key from the provided password using PBKDF2
27 + * @param password the password to derive a key from.
28 + * @param stream the stream used to prepend or retrieve the salt.
29 + * An <code>InputStream</code> is used for decryption, while an
30 + * <code>OutputStream</code> is used for encryption.
31 + * @return the password derived key.
32 + * @throws IOException if the salt has not been fully read.
33 + * @throws GeneralSecurityException if <code>stream</code> is not of type
34 + * <code>InputStream</code> or <code>OutputStream</code>.
35 + */
36 + static SecretKey deriveKey(char[] password, Object stream)
37 + throws IOException, GeneralSecurityException {
38 + // Add salt
39 + SecureRandom random = new SecureRandom();
40 + byte[] salt = new byte[SALT_SIZE];
41 + if (stream instanceof OutputStream) {
42 + // Generate salt and prepend to output
43 + random.nextBytes(salt);
44 + ((OutputStream) stream).write(salt);
45 + } else if (stream instanceof InputStream) {
46 + // Get prepended salt from input
47 + salt = ((InputStream) stream).readNBytes(SALT_SIZE);
48 + } else {
49 + throw new IllegalArgumentException("Argument stream must be of type" +
50 + " InputStream or OutputStream");
51 + }
52 +
53 + // Derive key
54 + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
55 + KeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_SIZE);
56 + SecretKey key = keyFactory.generateSecret(spec);
57 +
58 + return new SecretKeySpec(key.getEncoded(), CIPHER_ALGORITHM);
59 + }
60 +}
1 +package cryptor;
2 +
3 +import javax.swing.*;
4 +import javax.swing.filechooser.FileView;
5 +import java.awt.*;
6 +import java.awt.event.ActionEvent;
7 +import java.awt.event.ActionListener;
8 +import java.io.File;
9 +import java.io.FileNotFoundException;
10 +import java.io.FileOutputStream;
11 +import java.io.IOException;
12 +import java.security.GeneralSecurityException;
13 +import java.text.SimpleDateFormat;
14 +import java.util.Date;
15 +
16 +class LogWindow extends Frame {
17 +
18 + String fileIn;
19 +
20 + String fileName;
21 +
22 + String userId;
23 +
24 + String userPW;
25 +
26 +
27 + LogWindow(String title, String ID, String PW){
28 +
29 + //Frame(String title)을 호출한다.
30 +
31 + super(title);
32 +
33 + userId = ID;
34 + userPW = PW;
35 +
36 + //Label의 text정렬을 오른쪽으로
37 + String folderDir = ".\\" + userId + "\\logs";
38 +
39 + final File dirToLock = new File(folderDir);
40 + JFileChooser jfc = new JFileChooser(dirToLock);
41 + jfc.setFileView(new FileView() {
42 + @Override
43 + public Boolean isTraversable(File f) {
44 + return dirToLock.equals(f);
45 + }
46 + });
47 +
48 + jfc.showOpenDialog(null);
49 + fileIn = jfc.getSelectedFile().getAbsolutePath();
50 + fileName = jfc.getSelectedFile().getName();
51 +
52 + String passwd2 = userId + ' ' + userPW;
53 + char[] password2 = passwd2.toCharArray();
54 +
55 + String dir = fileIn.substring(0, fileIn.lastIndexOf('.')) + ".txt";
56 + File file = new File(dir);
57 + file.getParentFile().mkdir();
58 + try {
59 + file.createNewFile();
60 + } catch (IOException ioException) {
61 + ioException.printStackTrace();
62 + }
63 +
64 + try {
65 + Cryptor.decrypt(fileIn, dir, password2);
66 + } catch (IOException ioException) {
67 + ioException.printStackTrace();
68 + } catch (GeneralSecurityException generalSecurityException) {
69 + generalSecurityException.printStackTrace();
70 + }
71 +
72 + try {
73 + if(file.exists())
74 + {
75 + Desktop.getDesktop().open(file);
76 + }
77 + } catch (IOException ioException) {
78 + ioException.printStackTrace();
79 + }
80 +
81 + try {
82 + Thread.sleep(1000);
83 + } catch (InterruptedException interruptedException) {
84 + interruptedException.printStackTrace();
85 + }
86 + file.deleteOnExit();
87 + }
88 +
89 + public static void main(String args[]){
90 +
91 + LogWindow f = new LogWindow("Login", "user1", "12345678");
92 +
93 + }
94 +
95 +
96 +
97 + class EventHandler implements ActionListener{
98 +
99 + public void actionPerformed(ActionEvent e){
100 + dispose();
101 + }
102 +
103 + }
104 +
105 +}
...\ No newline at end of file ...\ No newline at end of file
1 +package cryptor;
2 +
3 +import java.io.IOException;
4 +import java.security.GeneralSecurityException;
5 +import java.util.Scanner;
6 +
7 +/**
8 + * Main entry point for running the Cryptor program.
9 + */
10 +public class Main {
11 +
12 + /**
13 + * Calls an encryption or decryption method according to command-line arguments.
14 + * If no arguments are given then command prompts will be shown.
15 + * @param args the command-line arguments.<br>
16 + * Arguments for encryption:
17 + * <ol>
18 + * <li>-encrypt</li>
19 + * <li>plaintext filename</li>
20 + * <li>encrypted filename</li>
21 + * <li>password</li>
22 + * </ol>
23 + * Arguments for decryption:
24 + * <ol>
25 + * <li>-decrypt</li>
26 + * <li>encrypted filename</li>
27 + * <li>decrypted filename</li>
28 + * <li>password</li>
29 + * </ol>
30 + */
31 + public static void main(String[] args)
32 + throws IOException, GeneralSecurityException {
33 +
34 + if (args.length > 0) {
35 + String mode = args[0];
36 + String inFile = args[1];
37 + String outFile = args[2];
38 + char[] password = args[3].toCharArray();
39 +
40 + if (mode.equals("-encrypt")) {
41 + Cryptor.encrypt(inFile, outFile, password);
42 + } else if (mode.equals("-decrypt")) {
43 + Cryptor.decrypt(inFile, outFile, password);
44 + } else {
45 + throw new GeneralSecurityException("Not a valid cipher mode");
46 + }
47 + } else {
48 + Scanner scan = new Scanner(System.in);
49 + System.out.print("Enter input filename: ");
50 + String fileIn = scan.nextLine();
51 +
52 + System.out.print("Enter output filename: ");
53 + String fileOut = scan.nextLine();
54 +
55 + System.out.print("Enter password: ");
56 + char[] password = scan.nextLine().toCharArray();
57 +
58 + System.out.print("Enter cipher mode [encrypt | decrypt]: ");
59 + String modeIn = scan.nextLine();
60 +
61 + if (modeIn.equals("encrypt")) {
62 + Cryptor.encrypt(fileIn, fileOut, password);
63 + } else if (modeIn.equals("decrypt")) {
64 + Cryptor.decrypt(fileIn, fileOut, password);
65 + } else {
66 + throw new GeneralSecurityException("Not a valid cipher mode");
67 + }
68 + }
69 + }
70 +}
1 +package cryptor;
2 +
3 +import javax.swing.*;
4 +import java.awt.*;
5 +import java.awt.event.ActionEvent;
6 +import java.awt.event.ActionListener;
7 +import java.awt.event.WindowAdapter;
8 +import java.awt.event.WindowEvent;
9 +import java.io.File;
10 +import java.io.FileNotFoundException;
11 +import java.io.FileOutputStream;
12 +import java.io.IOException;
13 +import java.security.GeneralSecurityException;
14 +import java.text.SimpleDateFormat;
15 +import java.util.Date;
16 +
17 +class MainMenu extends Frame {
18 +
19 + Button bRegister;
20 +
21 + Button bOpen;
22 +
23 + Button bViewLog;
24 +
25 + Button bDelete;
26 +
27 + MainMenu(String title, String ID, String PW){
28 +
29 + //Frame(String title)을 호출한다.
30 +
31 + super(title);
32 +
33 + addWindowListener(new WindowAdapter() {
34 + @Override
35 + public void windowClosing(WindowEvent e) {
36 + String folderDir = ".\\" + ID + "\\Decrypted";
37 + File folder = new File(folderDir);
38 + deleteDirectory(folder, ID, PW);
39 +
40 + dispose();
41 + System.exit(0);
42 + }
43 + });
44 +
45 + bRegister = new Button("Register Files");
46 +
47 + bOpen = new Button("Open Encrypted Files");
48 +
49 + bViewLog = new Button("View Logs");
50 +
51 + bDelete = new Button("Delete Encrypted Files");
52 +
53 + //OK버튼과 TextField에 이벤트처리를 위한 Listener를 추가해준다.
54 +
55 + bRegister.addActionListener(e -> {
56 + EncryptWindow f = new EncryptWindow(title, ID, PW);
57 + });
58 +
59 + bOpen.addActionListener(e -> {
60 + DecryptWindow f = new DecryptWindow(title, ID, PW);
61 + });
62 +
63 + bViewLog.addActionListener(e -> {
64 + LogWindow f = new LogWindow(title, ID, PW);
65 + });
66 +
67 + bDelete.addActionListener(e -> {
68 + DeleteEncypted f = new DeleteEncypted(title, ID, PW);
69 + });
70 +
71 + //LayoutManager를 FlowLayout으로
72 +
73 + setLayout(new FlowLayout());
74 +
75 + //생성한 component들을 Frame에 포함시킨다.
76 +
77 + add(bRegister);
78 +
79 + add(bOpen);
80 +
81 + add(bViewLog);
82 +
83 + add(bDelete);
84 +
85 + setSize(450,200);
86 +
87 + //화면이 보이게 한다.
88 +
89 + setVisible(true);
90 + }
91 +
92 + public static void main(String args[]){
93 + MainMenu f = new MainMenu("Main", "user1", "12345678");
94 + }
95 +
96 + public static boolean deleteDirectory(File path, String userId, String userPW) {
97 + if(!path.exists()) {
98 + return false;
99 + }
100 + File[] files = path.listFiles();
101 + for (File file : files) {
102 + if (file.isDirectory()) {
103 + deleteDirectory(file, userId, userPW);
104 + } else {
105 + String fileName = file.getName();
106 + String passwd2 = userId + ' ' + userPW;
107 + char[] password2 = passwd2.toCharArray();
108 + String dir = ".\\" + userId + "\\logs\\" + fileName + ".txt";
109 + String dir2 = ".\\" + userId + "\\logs\\" + fileName + ".log";
110 +
111 + try {
112 + Cryptor.decrypt(dir2, dir, password2);
113 + } catch (IOException ioException) {
114 + ioException.printStackTrace();
115 + } catch (GeneralSecurityException generalSecurityException) {
116 + generalSecurityException.printStackTrace();
117 + }
118 +
119 + FileOutputStream fos = null;
120 + try {
121 + fos = new FileOutputStream(dir,true);
122 + } catch (FileNotFoundException fileNotFoundException) {
123 + fileNotFoundException.printStackTrace();
124 + }
125 + SimpleDateFormat format1 = new SimpleDateFormat( "yyyy-MM-dd HH:mm");
126 +
127 + Date time = new Date();
128 +
129 + String time1 = format1.format(time);
130 + String toWrite = "삭제\t" + time1 + '\t' + "사용 완료" + '\n';
131 + byte[] b = toWrite.getBytes();
132 + try {
133 + fos.write(b);
134 + } catch (IOException ioException) {
135 + ioException.printStackTrace();
136 + }
137 + try {
138 + fos.flush();
139 + } catch (IOException ioException) {
140 + ioException.printStackTrace();
141 + }
142 + try {
143 + fos.close();
144 + } catch (IOException ioException) {
145 + ioException.printStackTrace();
146 + }
147 +
148 + try {
149 + Cryptor.encrypt(dir, dir2, password2);
150 + } catch (IOException ioException) {
151 + ioException.printStackTrace();
152 + } catch (GeneralSecurityException generalSecurityException) {
153 + generalSecurityException.printStackTrace();
154 + }
155 +
156 + File temp = new File(dir);
157 + temp.delete();
158 +
159 + file.delete();
160 + }
161 + }
162 + return path.delete();
163 + }
164 +}
...\ No newline at end of file ...\ No newline at end of file