최원종의 개발 블로그

FileInputStream / FileOutputStream 실습코드_2 본문

Java/JAVA 유용한 클래스

FileInputStream / FileOutputStream 실습코드_2

chl6698 2026. 3. 24. 14:04

-간단한 암호화 저장소

중요한 메모를 파일에 저장할 때 내용을 살짝 변환시켜서 저장

 

카이사르 암호

저장 방법은 저장할 때 각 문자의 ASCII코드에 숫자를 더하고 읽을 때는 더한 숫자만큼 빼서 원래 문자로 복원하는 방법

원본 텍스트 : Hello
암호화 후   : Khoor  (H+3=K, e+3=h, l+3=o, l+3=o, o+3=r)
복호화 후   : Hello  (K-3=H, h-3=e, o-3=l, o-3=l, r-3=o)

 


코드1

package io.ch15_1;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;

public class SecretNote1 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("=== 비밀 메모장 ===");
        System.out.println("1. 메모 암호화 저장");
        System.out.println("2. 메모 복호화 읽기");
        System.out.print("선택 : ");
        String choice = sc.nextLine();

        if(choice.equals("1")) {
            saveMemo(sc);
        } else if(choice.equals("2")) {
            readMemo();
        }

    }

    private static void readMemo() {
        System.out.println("\n=== 복호화된 메모 ===");
        try (FileInputStream fis = new FileInputStream("secret.txt")) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) (data - 3));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void saveMemo(Scanner sc) {

        System.out.print("저장할 메모를 입력하세요 : ");
        String input = sc.nextLine();

        try (FileOutputStream fos = new FileOutputStream("secret.txt")) {
            byte[] original = input.getBytes(); // [65][66][67] ...
            // 배열 크기만 선언한 상태
            byte[] encrypted = new byte[original.length]; // [65 + 3][66 + 3][67+ 3] ...

            for (int i = 0; i < original.length; i++) {
                encrypted[i] = (byte) (original[i] + 3);
            }

            // 데이터를 암호화 한 후 파일에 쓰기
            fos.write(encrypted);
            // fos.flush(); -> fos.close() 호출 시 자동 호출 flush()

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

-출력결과

더보기
선택 1번 후 메모 저장
저장된 Hello의 변환된 모습
복호화된 모습

-암호화 업그레이드 

카이사르 암호의  고정된 값(-3)이 아니라 사용자가 암호화 키 숫자를 입력한 만큼 암호화 되도록 만들기

실행 예시:
저장할 메모 : Hello
암호화 키   : 5
저장 완료!  (각 문자에 5를 더해서 저장)

복호화 키   : 5
복호화 결과 : Hello

 

-코드2

package io.ch15_1;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;

public class SecretNote2 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("=== 비밀 메모장 ===");
        System.out.println("1. 메모 암호화 저장");
        System.out.println("2. 메모 복호화 읽기");
        System.out.print("선택 : ");
        String choice = sc.nextLine();

        if (choice.equals("1")) {
            saveMemo(sc);
        } else if (choice.equals("2")) {
            readMemo(sc);
        }

    }

    private static void readMemo(Scanner sc) {
        System.out.print("복호화 키 :");
        int codeKey = sc.nextInt();
        System.out.println("\n=== 복호화된 메모 ===");
        try (FileInputStream fis = new FileInputStream("secret.txt")) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) (data - codeKey));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void saveMemo(Scanner sc) {

        System.out.print("저장할 메모를 입력하세요 : ");
        String input = sc.nextLine();
        System.out.print("암호화 키 : ");
        int codeKey = sc.nextInt();

        try (FileOutputStream fos = new FileOutputStream("secret.txt")) {
            byte[] original = input.getBytes(); // [65][66][67] ...
            // 배열 크기만 선언한 상태
            byte[] encrypted = new byte[original.length]; // [65 + 3][66 + 3][67+ 3] ...

            for (int i = 0; i < original.length; i++) {
                encrypted[i] = (byte) (original[i] + codeKey);
            }

            // 데이터를 암호화 한 후 파일에 쓰기
            fos.write(encrypted);
            // fos.flush(); -> fos.close() 호출 시 자동 호출 flush()

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

-출력결과

더보기
암호화 저장
암호화 키 만큼 바뀐 메모
키 값만큼 입력 시 복호화 된 모습
다른 키 값 입력시 출력되는 화면