Chapter01/Open API

[ NCP API ] encrypt / decrypt, signature 생성 예시 코드

EmmaDev_v 2025. 6. 2. 11:16

 

NCP (Naver Cloud Platform) API를 사용하려면

요청 인증을 하기 위해서 서명이 필요한데

 

 

HMAC-SHA256를 기반으로한 시그니처를 사용한다.

 

(이외에도 매번 accesskey, secretkey, timestamp 도 요구함)

 

이 중 아래 메서드에서 생성할 signature는 

서버가 위조나 변조 없이 API를 정상적으로 요청되었는지

검증하는 용도

 

 

 

        public String generateSignature(String timestamp, String url) throws Exception {
        String method = "POST";
        String space = " ";
        String newLine = "\n";

        String message = method + space + url + newLine + timestamp + newLine + accessKey;

        SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(rawHmac);
    }

 

 

 

 

 

 

 

 

cf. postman으로 테스트 요청을 날려보려고하는데도

이 시그니처를 먼저 생성해야해서

첨에 허둥지둥했던 기억에,,

 

포스트맨으로 요청 날릴때 사용한 스크립트일부는 아래

참고,,

var CryptoJS = require("crypto-js");
var btoa = require('btoa');

pm.environment.set('timestamp', Date.now().toString());

// 서명 생성 함수
function makeSignature() {
    var secretKey = 'ncp_iam_BGKSKR4FH9R28gEeNCAULe2Pbtp3QATqi';
    var accessKey = 'ncp_iam_BGASKR3fKGY0z8e2Qsa1'; 
    var timestamp = pm.environment.get('timestamp'); // 현재 타임스탬프
    
    // HMAC 생성
    var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secretKey);
    hmac.update("POST");
    hmac.update(" ");
    hmac.update("/keys/v2/a7d0cfcf7ed7a4e77708d1c5d71987f1b4fbb481c1b40d343859d238e62876aa/encrypt");
    hmac.update("\n");
    hmac.update(timestamp);
    hmac.update("\n");
    hmac.update(accessKey);

    var hash = hmac.finalize();

    // Base64로 인코딩하여 반환
    return hash.toString(CryptoJS.enc.Base64);
}

// 서명을 생성하여 환경 변수에 저장
var signature = makeSignature();
pm.environment.set('signature', signature);

요렇게 넣고

 

Header에

 

넣고

 

/encrypt 이면 

{
  "ciphertext": "Base64-encoded-encrypted-string"
}

 

/decrypt 이면

{
  "plaintext": "Base64-encoded-plaintext"
}

Body에 값 넣어주면된다

반응형