티스토리 뷰

공장 (factory)/- Programming..

[Java] HmacSHA1 암호화

무중력인간 2014. 9. 26. 20:30

   java 1.4 이상 버전에 있는 crypto를 이용해서 한다.


   Base64로 인코딩 하는 부분은 apache commons-codec 라이브러리를 사용했다. 

   다운로드 ☞ http://commons.apache.org/proper/commons-codec/download_codec.cgi


commons-codec-1.9.jar


   참고한 사이트 ☞ https://gist.github.com/ishikawa/88599


   아래 코드를 보고 눈치챈 사람도 있겠지만,, crypto를 이용해 다른 알고리즘으로 암호화/복호화도 가능하다.

   자세히 알고 싶다면 ☞ http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyGenerator



import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.util.Formatter; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class HmacSha1Signature { private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; /** * @description byte 배열을 16진수로 변환한다. */ private static String toHexString(byte[] bytes) { Formatter formatter = new Formatter(); for (byte b : bytes) { formatter.format("%02x", b); } return formatter.toString(); } /** * @description byte 배열을 Base64로 인코딩한다. */ public static String toBase64String(byte[] bytes){ byte[] byteArray = Base64.encodeBase64(bytes); return new String(byteArray); } /** * @description HmacSHA1로 암호화한다. (HmacSHA1은 hash algorism이라서 복호화는 불가능) */ public static String encryption(String data, String key) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException { SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); return toBase64String(mac.doFinal(data.getBytes())); } public static void main(String[] args) throws Exception { String encryptedStr = encryption("hi there~", "UDn3AE4fHoltof0XjcdUQ"); System.out.println("encryptedStr : " + encryptedStr); } }


   출력한 결과가 "encryptedStr : nV4nFMIohfC/P9X0w51FFCMLocg=" 이렇게 나왔다면 OK.



댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함