Hash Filter 개발
    • PDF

    Hash Filter 개발

    • PDF

    Article Summary

    Classic/VPC 환경에서 이용 가능합니다.

    Hash Filter REST API를 사용하여 Hash Filter 코드를 작성하는 방법을 설명합니다.

    참고

    Hash Filter 개발에 앞서 File Safer 이용 신청, API Gateway 이용 신청 및 API Key 생성을 해야 합니다. 자세한 내용은 File Safer 시작을 참조해 주십시오.

    Hash Filter 구현 시나리오

    사용자가 업로드/다운로드 하는 파일에 대한 Hash Filter 적용 시나리오는 다음과 같습니다.

    filesafer-programming-hash_scenario_ko

    1. 악성 코드로 의심되는 파일을 구분
    2. 구분된 파일에서 Hash 값 추출
    3. 인증값 생성
    4. 요청 파라미터 추가
    5. API 요청
    6. 응답 값 확인 및 차단 여부 판단

    Hash Filter 코드 작성

    Hash Filter 구현 시나리오에 따라 코드를 작성해 주십시오.

    1. 악성 코드로 의심되는 파일을 구분

    업로드/다운로드 되는 파일 중에 악성 코드 검사가 필요한 파일을 구분해 주십시오.

    2. 구분된 파일에서 Hash 값 추출

    파일에서 Hash 값을 추출해 주십시오. 다음은 Hash 값을 추출하는 JAVA 예제 코드입니다.

    참고

    Hash 타입별 Hash 값의 표기 양식은 다음과 같습니다.

    • SHA-1: 16진수 40 bytes 스트링으로 표기
      <예시> 3ec625cb2277d7334406ab712b69c4ceaf38bd82
    • MD5: 16진수 32 bytes 스트링으로 표기
      <예시> 8072fd6da170738c905cf362f787442b
    public static String getHash(String filename, String algorithm) throws Exception
    {
    	MessageDigest md = MessageDigest.getInstance(algorithm);
    
    	// file hashing with DigestInputStream
    	DigestInputStream dis = new DigestInputStream(new FileInputStream(new File(filename)), md);
    
    	// empty loop to clear the data
    	while(dis.read() != -1);
    	dis.close();
    
    	// Get the hash's bytes
    	byte[] hashBytes = md.digest();
    
    	// bytes to hex
    	StringBuffer sb = new StringBuffer();
    	for(byte h : hashBytes) {
    		sb.append(String.format("%02x", h));
    	}
    
    	return sb.toString();
    }
    
    public static void main(String[] args)
    {
        try {
            // Get hash value of a file with SHA-1 Algorithm
            String sha1 = getHash("./test.exe", "sha-1");
            // Get hash value of a file MD5 Algorithm
            String md5 = getHash("./test.exe", "md5");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    

    3. 인증값 생성

    네이버 클라우드 플랫폼 API 사용 인증에 필요한 IAM 인증값을 생성해 주십시오. 인증에 필요한 헤더는 다음과 같습니다.

    • x-ncp-iam-access-key: 네이버 클라우드 플랫폼 포털의 마이페이지 > API 인증키 관리 메뉴에서 Access Key 발급
    • x-ncp-apigw-signature-v2 : Access Key와 매핑되는 Secret Key를 HmacSHA256 암호화하여 signature 값 생성 (개행 문자는 \n 사용)
    • x-ncp-apigw-api-key : API Gateway를 통해 API Key 발급
    • x-ncp-apigw-timestamp : 인증값은 아니지만 요청 헤더에 포함. API 명세 참고
    참고

    signature 값을 생성하는 방법과 예제 코드는 네이버 클라우드 플랫폼 API 가이드 > API 개요 > 기본 API > Ncloud API > 2.헤더 생성을 참조해 주십시오.

    4. 요청 파라미터 추가

    Hash Filter API 요청 파라미터 값을 추가해 주십시오. 요청 파라미터는 다음과 같습니다.

    • hashCode: Hash 값을 스트링으로 추가
    • hashType: Hash 값의 알고리즘을 표기(MD5 또는 SHA-1)

    다음은 생성된 파라미터 예시입니다.

    hashCode=00010efc49b7174d18400710eed1642a7d4b12db&hashType=sha1
    
    참고

    Hash Filter REST API의 명세는 checkHash (Hash Filter)를 참조해 주십시오.

    5. API 요청

    위의 3번과 4번 절차에서 생성한 헤더와 파라미터를 사용하여 Hash Filter URI로 요청해 주십시오. 다음은 Hash Filter API 요청 예제 코드입니다.

    public static void main(String[] args) throws Exception
    {
    	String accessKey = "ACCESS_KEY"; // access key (from portal or sub account)
        String apikey = API_GATEWAY_KEY;
    	String apiDomain = "https://filesafer.apigw.ntruss.com";
    	String method = "GET";
    	long timestamp = System.currentTimeMillis();   
     
    	// step 2, 3: Extract hash vlaue of a identified file then add parameter value including hash value and hash type
    	String param = "hashCode=" + getHash("./test.exe") + "&hashType=sha1";
    	// The apiURL is the value obtained by appending parameter to the end of URI string provided by Hash Filter.
    	String apiURL = "/hashfilter/v1/checkHash?" + param;
    
    	// step 4: Create authentication value
    	String signature = makeSignature(method, apiURL, timestamp);
    
    	// step 5: Request API
    	URL url = new URL(apiDomain + apiURL);
    	HttpURLConnection con = (HttpURLConnection)url.openConnection();
    	con.setRequestMethod(method);
    	con.setRequestProperty("x-ncp-apigw-timestamp", Long.toString(timestamp));
    	con.setRequestProperty("x-ncp-iam-access-key", accessKey);
    	con.setRequestProperty("x-ncp-apigw-signature-v2", signature);
        con.setRequestProperty("x-ncp-apigw-api-key", apikey);
    	con.setRequestProperty("accept", "application/json");
    
    	// step 6: Check the response value and determine whether to block
    	int httpResponseCode = con.getResponseCode();
    	BufferedReader br = null;
    	if (httpResponseCode == 200) {
    		br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    
    		String readLine;
    		StringBuffer httpResponse = new StringBuffer();
    
    		while((readLine = br.readLine())! = null) {
    			httpResponse.append(readLine);
    		}
    
    		// Do next step (ex, determine whether to block)
    		...
    
    		br.close();
    	}
    }
    
    참고

    jdk20 이상 사용 시 URL 메소드 대신 URI 메소드를 사용할 수 있습니다.

    6. 응답 값 확인 및 차단 여부 판단

    API 호출 응답 값의 hashCheckResultListobject 값을 보고 악성 코드 유무를 판단하여 파일을 처리해 주십시오.
    hashCheckResultListobject가 있을 경우 악성 코드가 탐지된 것이고, 그렇지 않을 경우 악성 코드가 없는 것입니다.


    이 문서가 도움이 되었습니까?

    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.