본문 바로가기

Java

(JAVA) - JCE 암호화 복호화 찍먹하기

반응형

🍳머리말

Java Cryptography Extension (JCE) 표준 library를 이용해 secret key를 발급받는 예제 code입니다.


📕설명

📔 secret key 생성

📑 code

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;

public class SecretKeyExample {

    public static void main(String[] args) throws Exception {
        // Create a KeyGenerator
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");

        // Initialize the KeyGenerator with a key size
        keyGen.init(128); // for AES-128. Use 192 for AES-192, or 256 for AES-256.

        // Generate the secret key
        SecretKey secretKey = keyGen.generateKey();

        // Get the bytes of the secret key
        byte[] secretKeyBytes = secretKey.getEncoded();

        // To use this key later, you might want to store it somewhere.
        // Here we'll just print the key to the console.
        System.out.println("Secret Key: " + Base64.getEncoder().encodeToString(secretKeyBytes));
    }
}

📑 결과

Secret Key: QsbkGrY4rVYlVy6t/z25Bw==

📔 암호화

📑 code

문자열 data를 byte배열로 바꾼뒤 string으로 encode하게 됩니다.

public static String encrypt(String data, String secretKey) {
    try {
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedByteValue = cipher.doFinal(data.getBytes("utf-8"));
        return Base64.getEncoder().encodeToString(encryptedByteValue);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

📔 복호화

📑 code

문자열 data를 byte배열로 바꿔 decrypt후 반환합니다.

public static String decrypt(String data, String secretKey) {
    try {
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedValue64 = Base64.getDecoder().decode(data);
        byte[] decryptedByteValue = cipher.doFinal(decryptedValue64);
        return new String(decryptedByteValue, "utf-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

📔 종합

📑 code

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.sql.*;
import java.util.Base64;

public class EncryptionExample {

    private static final String SECRET_KEY = "QsbkGrY4rVYlVy6t/z25Bw=="; // Replace with your actual secret key
    private static final String ALGORITHM = "AES";

    public static void main(String[] args) {
        String originalText = "35";
        String encryptedText = encrypt(originalText, SECRET_KEY);
        String decryptedText = decrypt(encryptedText, SECRET_KEY);

        System.out.println("Original: " + originalText);
        System.out.println("Encrypted: " + encryptedText);
        System.out.println("Decrypted: " + decryptedText);
    }

    public static String encrypt(String data, String secretKey) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encryptedByteValue = cipher.doFinal(data.getBytes("utf-8"));
            return Base64.getEncoder().encodeToString(encryptedByteValue);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String decrypt(String data, String secretKey) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptedValue64 = Base64.getDecoder().decode(data);
            byte[] decryptedByteValue = cipher.doFinal(decryptedValue64);
            return new String(decryptedByteValue, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

📑 결과


*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.