daily pastebin goal
30%
SHARE
TWEET

Android Hash

Nesswit Apr 20th, 2013 363 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class Hash {
  2.    
  3.     /**
  4.      * 16진수를 문자열로 변환
  5.      * @param data 변환할 16진수
  6.      * @return 변환된 16진수 문자열
  7.      */
  8.     private static String convertToHex(byte[] data) {
  9.         StringBuilder buf = new StringBuilder();
  10.         for (byte b : data) {
  11.             int halfbyte = (b >>> 4) & 0x0F;
  12.             int two_halfs = 0;
  13.             do {
  14.                 buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
  15.                 halfbyte = b & 0x0F;
  16.             } while (two_halfs++ < 1);
  17.         }
  18.         return buf.toString();
  19.     }
  20.  
  21.     /**
  22.      * 문자열의 SHA-1 해쉬값 얻기
  23.      * @param text SHA-1 해쉬값을 얻어올 문자열
  24.      * @return text 의 SHA-1 해쉬 String
  25.      */
  26.     public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
  27.         MessageDigest md = MessageDigest.getInstance("SHA-1");
  28.         md.update(text.getBytes("iso-8859-1"), 0, text.length());
  29.         byte[] sha1hash = md.digest();
  30.         return convertToHex(sha1hash);
  31.     }
  32.  
  33.     /**
  34.      * 문자열의 HMAC 해쉬값 얻기
  35.      * @param type 사용할 HMAC 알고리즘 ("HmacSHA1")
  36.      * @param value HMAC 해쉬값을 얻어올 문자열
  37.      * @param key HMAC 해쉬값 생성에 필요한 key
  38.      * @return value 의 HMAC 해쉬 String
  39.      */
  40.     public static String HMAC(String type, String value, String key) throws NoSuchAlgorithmException, InvalidKeyException{
  41.         javax.crypto.Mac mac = javax.crypto.Mac.getInstance(type);
  42.         javax.crypto.spec.SecretKeySpec secret = new javax.crypto.spec.SecretKeySpec(key.getBytes(), type);
  43.         mac.init(secret);
  44.         byte[] digest = mac.doFinal(value.getBytes());
  45.         StringBuilder sb = new StringBuilder(digest.length*2);
  46.         String s;
  47.         for (byte b : digest){
  48.             s = Integer.toHexString(b&0xFF);
  49.             if(s.length() == 1) sb.append('0');
  50.             sb.append(s);
  51.         }
  52.         return sb.toString();
  53.     }
  54.  
  55. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top