STUDY/Assignment

자바 프로젝트(txt 암복호화 프로그램)

da1seun9 2021. 12. 16. 22:34
//main//
package Cipher_project;

import java.util.Scanner;
import Cipher_project.Writetxt;
import Cipher_project.Encrypt;
import Cipher_project.Deletetxt;

public class Encrypt_Example {
    public static void main(String[] args) throws Exception {
        int divide;
        Encrypt cipher = new Encrypt();
        Writetxt w = new Writetxt();
        Deletetxt d = new Deletetxt();
        Scanner scanner = new Scanner(System.in);
        System.out.println("************************************************************");
        System.out.println("                   < texlock 이용 시 주의사항 >         ");
        System.out.println("             1. 암호는 반드시 16자 이상 할 것.             ");
        System.out.println("             2. 암호는 영어와 숫자, 특수문자까지 섞어서 만들 것. ");
        System.out.println("             3. txt파일은 UTF-8로 해야 한글 사용 가능.      ");
        System.out.println("             4. 암호 절대절대 까먹지 않기 :(               ");
        System.out.println("************************************************************\n\n");
        while(true) {

        System.out.println("-------------------------프로그램 시작-------------------------");
        System.out.println("1. 퍄일 암호화");
        System.out.println("2. 파일 복호화");
        System.out.println("3. 파일 생성");
        System.out.println("4. 파일 삭제");
        System.out.printf("어떤 것을 하시겠습니까? : ");

        divide = scanner.nextInt();

        switch(divide) {
            case 1:
                cipher.encrypt();
                break;
            case 2:
                cipher.decrypt();
                break;
            case 3:          // 파일 생성
                w.Write();
                break;
            case 4:
                d.Delete();
                break;
            default:
                System.out.println("oh.... Choose again :(");
                break;
        }
    }
    }
}
// Encrypt 및 Decrypt 함수
package Cipher_project;

import java.util.Base64;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import Cipher_project.Readtxt;
import Cipher_project.Writetxt;

public class Encrypt {

    private static String alg = "AES/CBC/PKCS5Padding";
    private String key;
    private String iv; // 16byte
    private String text;
    private String cipher_text;
    private String path;

    public void encrypt(){
        try{
        Readtxt t = new Readtxt();
        Writetxt w = new Writetxt();
        this.path = t.Read();

        Scanner s = new Scanner(System.in);
        System.out.printf("16자리 숫자키 입력 : ");
        this.key = s.nextLine();
        this.text = t.text;
        this.iv = key.substring(0, 16);                                          // 인덱스 0부터 15까지의 문자열을 받음

        Cipher cipher = Cipher.getInstance(alg);                                 // aes 객체 생성
        SecretKeySpec keySpec = new SecretKeySpec(iv.getBytes(), "AES");         // getbytes()는 String 문자열을 byte코드로 바꾸는 역할 AES로 키를 생성하는 객체를 생성
        IvParameterSpec ivParamSpec = new IvParameterSpec(iv.getBytes());        // IV(초기화 벡터)를 생성 IV란 첫 블록을 암호화할 때 사용하는 값이다. IV객체를 생성한다.
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParamSpec);                  // 위에서 정해진 key와 IV를 이용하여 암호화모드룰 사용하겠다는 초기화

        byte[] encrypted = cipher.doFinal(this.text.getBytes("UTF-8"));          // Cipher 객체를 초기화한 후에, 암호화 또는 복호화 작업을 위해 doFinal() 메서드를 호출할 수 있다. 
                                                                                 // 해당 메서드는 암호화 또는 복호화된 메세지를 포함한 byte 배열을 반환한다.
        this.cipher_text = Base64.getEncoder().encodeToString(encrypted);

        w.Write(path, cipher_text);
        System.out.println("-------------------------암호화 완료-------------------------");
        }
        catch(Exception e) {
            System.out.println("시스템 오류로 프로그램을 종료합니다.");
            System.out.println("다시 시도해주십시오.");
        }
    }

    public void decrypt(){

        try {
        Readtxt t = new Readtxt();
        Writetxt w = new Writetxt();
        this.path = t.Read();

        Scanner s = new Scanner(System.in);
        System.out.printf("16자리 숫자키 입력 : ");
        this.key = s.nextLine();

        this.cipher_text = t.text;
        this.iv = key.substring(0, 16);

        Cipher cipher = Cipher.getInstance(alg);
        SecretKeySpec keySpec = new SecretKeySpec(iv.getBytes(), "AES");
        IvParameterSpec ivParamSpec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParamSpec);

        byte[] decodedBytes = Base64.getDecoder().decode(this.cipher_text);
        byte[] decrypted = cipher.doFinal(decodedBytes);
        this.text = new String(decrypted, "UTF-8");
        w.Write(path, text);
        System.out.println("-------------------------복호화 완료-------------------------");
        }
        catch(Exception e) {
            System.out.println("보안을 위해 프로그램을 종료합니다.");
            System.out.println("-------------------------The End-------------------------");
        }
    }

}​
// txt파일을 읽는 함수
package Cipher_project;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Readtxt {                                            // 한글깨짐을 막기위해 인코딩 설정을 할 수 있는 FileInputStream, FileOutputStream를 사용

    public String text = "";
    public String newpath;
    public String Read(){
    Scanner path = new Scanner(System.in);
    try {
        System.out.print("파일 경로를 입력하세요 : ");
        newpath = path.nextLine();
        File file = new File(newpath);
        FileReader file_reader = new FileReader(file);
        int result = 0;
        while((result = file_reader.read()) != -1) {
            text += (char)result;
        }

        file_reader.close();
        }
    catch(FileNotFoundException e) {
        System.out.println("파일이 존재하지 않습니다.");
        System.out.println("프로그램을 종료합니다.");
        System.exit(0);
        }
    catch(IOException e) {
        System.out.println("입력 오류");
        System.out.println("프로그램을 종료합니다.");
        System.exit(0);
        }
    return this.newpath;
    }
}
// txt를 덮어쓰거나 만드는 함수
package Cipher_project;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;


public class Writetxt {
    FileWriter fw, fw_append;
    Scanner path = new Scanner(System.in);
    String WritePath;
    Scanner s = new Scanner(System.in);
    String a;

    public void Write(String path ,String c_t) {
        try {
            this.WritePath = path;
            this.fw = new FileWriter(WritePath, false);
            this.a = c_t;
            fw.write(this.a);
            fw.close();
        }
        catch(IOException e1) {
            e1.printStackTrace();
        }
        return;
    }

    public void Write() {
        try {
            System.out.println("어떤 경로에 만들 건가요?");
            WritePath = path.nextLine();
            fw = new FileWriter(WritePath, false);
            System.out.println("내용을 입력하세요.");
            this.a = s.nextLine();
            fw.write(this.a);
            fw.close();
        }
        catch(IOException e) {
            System.out.println("에러");
            System.out.println("시스템 종료");
            System.exit(0);
        }
    }
    // 파일 삭제 //
package Cipher_project;

import java.io.File;
import java.util.Scanner;

public class Deletetxt {
    public String File_path;
    Scanner s = new Scanner(System.in);

    void Delete() {
        System.out.println("삭제할 파일 경로를 입력하세요");
         this.File_path = s.nextLine();
         File deleteFile = new File(File_path);

        if(deleteFile.exists()) {
            deleteFile.delete();
            System.out.println("파일을 삭제하였습니다.");
        }
        else {
            System.out.println("파일이 존재하지 않습니다.");
            System.out.println("시스템을 종료합니다.");
            System.exit(0);
        }
    }
}

'STUDY > Assignment' 카테고리의 다른 글

객체 지향 과제 rep 8-2  (0) 2020.06.09
객체 지향 과제 rep 8-1  (0) 2020.06.05
객체 지향 과제 rep7  (0) 2020.05.30
객체 지향 과제 rep6  (0) 2020.05.18
보안 자료 구조 과제  (0) 2020.05.04