본문 바로가기
개발/JAVA

Cipher을 통한 암호화

by 설이주인 2024. 2. 21.

서비스를 개발하면서 양방향으로 암호화를 진행해야하는 정보들이 존재하여 Cipher로 작업한 부분을 남긴다.

 

@Component
public class CipherHelper {

public static String alg = "7E6YRDQ59E9UTAM9M3G4OJU2RZTGF6K4";
private static final String key = "AES/CBC/PKCS5Padding";
private static final String iv = key.substring(0, 16); // 16byte

public static String encrypt(String text) throws Exception {
    /**
        * Cipher : AES 및 다양한 암호화 알고리즘을 사용하여 데이터를 암호화하고 해독하는 메서드를 제공한다.
        *
        * In order to create a Cipher object, the application calls the Cipher's getInstance
        * method, and passes the name of the requested transformation to it.
        * Optionally, the name of a provider may be specified.
        *
        *
        * A transformation ["algorithm/mode/padding" or "algorithm"] always includes the name of
        * a cryptographic algorithm (e.g., AES), and may be followed by a feedback mode and padding scheme.
        *
        * transformation >
        * AES/CBC/NoPadding (128)
        * AES/CBC/PKCS5Padding (128)
        * AES/ECB/NoPadding (128)
        * AES/ECB/PKCS5Padding (128)
        * AES/GCM/NoPadding (128)
        * DES/CBC/NoPadding (56)
        * DES/CBC/PKCS5Padding (56)
        * DES/ECB/NoPadding (56)
        * DES/ECB/PKCS5Padding (56)
        * DESede/CBC/NoPadding (168)
        * DESede/CBC/PKCS5Padding (168)
        * DESede/ECB/NoPadding (168)
        * DESede/ECB/PKCS5Padding (168)
        * RSA/ECB/PKCS1Padding (1024, 2048)
        * RSA/ECB/OAEPWithSHA-1AndMGF1Padding (1024, 2048)
        * RSA/ECB/OAEPWithSHA-256AndMGF1Padding (1024, 2048)
        *
        */
    Cipher cipher = Cipher.getInstance(alg);

    /**
        * SecretKeySpec : 비밀키를 만드는 데 사용된다.
        *
        * This class specifies a secret key in a provider-independent fashion.
        * It can be used to construct a SecretKey from a byte array, without having to go through
        * a (provider-based) SecretKeyFactory. This class is only useful for raw secret keys that can be
        * represented as a byte array and have no key parameters associated with them, e.g., DES or Triple DES keys.
        *
        * AES : AES(Advanced Encryption Standard)
        * */
    SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");

    /**
        * IvParameterSpec : CBC 모드의 IV(초기치)를 만들기 위해 사용한다.
        * 블록 암호 운용 방식 중 초기치(IV)가 필요한 모드에 초기치(IV)를 만들기 위해 사용합니다.
        * CBC : 암호 블록 연결(CBC, Cipher Block Chaining) 모드
        * */
    IvParameterSpec ivParamSpec = new IvParameterSpec(iv.getBytes());

    /**
        * AES ECB : 초기치(IV)가 필요하지 않음
        * AES CBC : 초기치(IV)가 필요함
        * */


    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParamSpec);

    byte[] encrypted = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
    return Base64Utils.encodeToUrlSafeString(encrypted);
}

public static  String decrypt(String cipherText) {
    try {
        if (cipherText.matches("[+-]?\\d*(\\.\\d+)?")) {
            return cipherText;
        }

        Cipher cipher = Cipher.getInstance(alg);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivParamSpec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParamSpec);
        byte[] decodedBytes = Base64Utils.decodeFromUrlSafeString(cipherText);
        byte[] decrypted = cipher.doFinal(decodedBytes);
        return new String(decrypted, StandardCharsets.UTF_8);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
}

 

 

참고 링크

https://m.blog.naver.com/hj_kim97/222717777281

 

[Java]Java AES 암호화 하기(AES-128, AES-192, AES-256)

Java AES 암호화(AES-128, AES-192, AES-256) ▶ 대칭키 암호란? ▶ AES 암호화란? ▶ 블...

blog.naver.com

https://hongik-prsn.tistory.com/75

 

JAVA 암호화와 복호화 Cipher

먼저 암호화라는 개념은 너무나 간단합니다 내가 가진 원문의 메세지를 상대방이 해석할 수 없게 하는 것이 바로 암호화의 목적 javax.crypto.Cipher 클래스는 암호화 알고리즘을 나타낸다. 암호를

hongik-prsn.tistory.com

https://green-bin.tistory.com/50#AES-Advanced%25--Encryption%25--Standard-%25--%EC%25--%25--%ED%25--%25B-%ED%25--%25--

 

Java - AES-128 양방향 암호화하기

RefreshToken을 쿠키로 전달할 때 보안을 강화하기 위해 AES128 양방향 암호화를 적용했다. RefreshToken은 사용자가 재인증할 필요 없이 새로운 AcessToken을 발급받도록 해준다. 만약 해커가 RefreshToken을

green-bin.tistory.com