개발일기 정답찾기

HMAC SHA256 라이브러리, commons-codec-1.15.jar 암호화 하기 - 유딩동 Tistory 본문

IT/기타

HMAC SHA256 라이브러리, commons-codec-1.15.jar 암호화 하기 - 유딩동 Tistory

유딩동 2021. 6. 6. 12:47

안녕하세요, 유딩동입니다.

 

HMAC SHA256 알고리즘에 대한 글입니다.

 

 

암호학에서 HMAC(keyed-hash message authentication code, hash-based message authentication code)는 암호화 해시 함수와 기밀 암호화 키를 수반하는 특정한 유형의 메시지 인증 코드(MAC)이다. 여느 MAC처럼 메시지의 데이터 무결성과 진본 확인을 동시에 수행하기 위해 사용할 수 있다.  - 위키백과
public class HmacAlTest {
public static void main(String[] args) {
		String key = "encrpyt12345";
		String tempStr = "udingdong";

		System.out.println(new HmacUtils(HmacAlgorithms.HMAC_SHA_256, key).hmacHex(tempStr));
		System.out.println(hget(tempStr));

}
    // 알고리즘 선택
    private static final String ALGOLISM = "HmacSHA256";
    // 암호화 key
    private static final String key = "encrpyt12345";

    public static String hget(String message) {
        try {
            // 알고리즘과 암호화 key 적용
            Mac hasher = Mac.getInstance(ALGOLISM);
            hasher.init(new SecretKeySpec(key.getBytes(), ALGOLISM));

            // 암호화 적용 후 byte 배열 형태의 결과
            byte[] hash = hasher.doFinal(message.getBytes());
            return byteToString(hash);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    // byte[]의 값을 16진수 형태 문자로 변환
    private static String byteToString(byte[] hash) {
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < hash.length; i++) {
            int d = hash[i];
            d += (d < 0)? 256 : 0;
            if (d < 16) {
                buffer.append("0");
            }
            buffer.append(Integer.toString(d, 16));
        }
        return buffer.toString();
    }

}

 

두가지 방법이 있습니다.

 

1. commons-codec-1.15.jar

해당 함수에 대하여, 1.15버전부터 제공하므로 해당 jar를

임포트 하시면 바로 사용 가능합니다.

 

저같은 경우에는 해당 라이브러리가 다른 버전이 이용되고 있다 보니

기존 소스에 대한 위험도 때문에 구현하는 방법으로 진행 했습니다.

 

https://commons.apache.org/proper/commons-codec/download_codec.cgi

 

Codec – Download Apache Commons Codec

Download Apache Commons Codec Using a Mirror We recommend you use a mirror to download our release builds, but you must verify the integrity of the downloaded files using signatures downloaded from our main distribution directories. Recent releases (48 hou

commons.apache.org

 

다운하실 수 있습니다.

 

2. 알고리즘, key를 선언한 후 함수로 구현

 

 

 

Comments