본문 바로가기

⭐ AWS/KMS (KeyManagementService)

KMS와 SpringBoot연동 후 특정 필드 암 복호화 하기

# KMS와 SpringBoot를 연동하고 RDS의 특정 필드를 암 복호화 하기

1. KMS 서비스 생성하기

- 서비스 생성하는 과정을 어렵지 않으니, 생략하고 여기서 나는 e-mail을 암호화 하도록 설정 하였다.

2. 고객 관리형 키 확인

- 고객 관리형 키를 확인하면 아래와 같다.

해당 키를 Spring에 입력 후 키값을 조회 할 수 있다.

3. SpringBoot와 연동하기

- 일단 SpringBoot와 연동하기 위해서는 자격증명을 해야한다.

CMD 에서 aws configure를 통해 해당 사용자의 자격증명을 수행한다.

4. SpringBoot application.yml에 KMS 정보 등록하기

aws:
  secretsmanager:
    name: #secretmanager service name
  kms:
    keyId: "888888-44444-5555-9999-888888888"
    encryptionAlgorithm: "RSAES_OAEP_SHA_256"
cloud:
  aws:
    region:
      static: ap-northeast-2

5. 입력받은 값을 DB에 암호화 하여 Insert 수행

@RequiredArgsConstructor
@RestController
public class KmsController {

    private final KmsServiceImpl kmsServiceEnv;
    @GetMapping("/encrypt")
    public String encrypt(@RequestParam String plainText, String name) {

        return kmsServiceEnv.encrypt(plainText, name);
    }

    @PostMapping("/encrypt_insert_email")
    public String encrypt_insert_email(@RequestParam String staff_email, String name) {

        return kmsServiceEnv.encrypt(staff_email, name);
    }

    @GetMapping("/decrypt_select_email")
    public String decrypt(@RequestParam String name) {

        return kmsServiceEnv.decrypt(name);
    }
}

- KmsServiceImpl.java 파일 작성

@Slf4j
@Service
public class KmsServiceImpl {
    @Value("${aws.kms.keyId}")
    private String KEY_ID;

    @Autowired KmsService kmsService;

    public String encrypt(String staff_email, String name) {
        try {
            AWSKMS kmsClient = AWSKMSClientBuilder.standard()
                    .withRegion(Regions.AP_NORTHEAST_2)
                    .build();

            EncryptRequest request = new EncryptRequest();
            request.withKeyId(KEY_ID);
            request.withPlaintext(ByteBuffer.wrap(staff_email.getBytes(StandardCharsets.UTF_8)));
            request.withEncryptionAlgorithm(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256);

            EncryptResult result = kmsClient.encrypt(request);
            ByteBuffer ciphertextBlob = result.getCiphertextBlob();

            // 암호화 값을 가져와서 String으로 담는다.
            String result_encrypt = new String(Base64.encodeBase64(ciphertextBlob.array()));

            // 암호화 값 log로 확인하기
            log.info("result_encrypt :: " + result_encrypt);

            // DB INSERT
            kmsService.encrypt_insert_email(result_encrypt, name);

            return new String(Base64.encodeBase64(ciphertextBlob.array()));
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    public String decrypt(String name) {
        try {
            AWSKMS kmsClient = AWSKMSClientBuilder.standard()
                    .withRegion(Regions.AP_NORTHEAST_2)
                    .build();

            // 암호화된 값을 DB에서 가져온다.
            String encrypted_value = kmsService.get_encrypt_value(name);

            DecryptRequest request = new DecryptRequest();
            request.withCiphertextBlob(ByteBuffer.wrap(Base64.decodeBase64(encrypted_value)));
            request.withKeyId(KEY_ID);
            request.withEncryptionAlgorithm(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256);
            ByteBuffer plainText = kmsClient.decrypt(request).getPlaintext();

            // 암호화 값을 가져와서 String에 담는다.
            String result_decrypt = new String(plainText.array());

            // 복호화된 값을 화면에 출력한다.
            log.info("복호화된 값 ::" + result_decrypt);
            return new String(plainText.array());
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }
}

6. DB에서 확인하기

- 아래와 같이 Postman으로 데이터를 Insert하면 DB에 등록된다.

- DB 등록 현황은 아래와 같다.

7. 복호화 하기

- 위와 같이 해당 사용자 이름을 확인하여 e-mail 정보를 복호화 할 수 있다.

- KMS는 단지 암호화 및 복호화 위한 서비스이고, KMS ID와 암호 알고리즘을 SpringBoot에 등록하면 사용이 가능하다. 

대신 별칭에 DB의 컬럼값이 들어가며 암호 알고리즘 등을 선택 할 수 있다.

그리고 KMS 서비스에서 키 정책, 키 관리자, 키 삭제, 키 사용자 등을 설정하여 세부적으로 관리가 가능하다.

 

- 끝 -