Last active
January 2, 2016 14:39
-
-
Save diablowu/8318372 to your computer and use it in GitHub Desktop.
hmacwithsha1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util; | |
import java.security.InvalidKeyException; | |
import java.security.NoSuchAlgorithmException; | |
import javax.crypto.Mac; | |
import javax.crypto.spec.SecretKeySpec; | |
public class SignTools { | |
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; | |
private static final char[] DIGIT = { '0', '1', '2', '3', '4', '5', '6', | |
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; | |
/** | |
* 使用hmacsha1安全摘要算法生成摘要 | |
* @param data 需要摘要的字符串 | |
* @param key 摘要使用的密钥 | |
* @return 如果计算失败则返回null | |
*/ | |
public static String sign(String data, String key){ | |
String dgst = null; | |
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),HMAC_SHA1_ALGORITHM); | |
Mac mac = null; | |
try { | |
mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); | |
mac.init(signingKey); | |
byte[] dg = mac.doFinal(data.getBytes()); | |
StringBuffer sb = new StringBuffer();//StringBuilder | |
for (int i = 0; i < dg.length; i++) { | |
sb.append(hexString(dg[i])); | |
} | |
dgst = sb.toString(); | |
} catch (NoSuchAlgorithmException e) { | |
//ignore | |
} catch (InvalidKeyException e) { | |
e.printStackTrace(); | |
} | |
return dgst; | |
} | |
private static String hexString(byte b) { | |
char[] ob = new char[2]; | |
ob[0] = DIGIT[(b >>> 4) & 0X0F]; | |
ob[1] = DIGIT[b & 0X0F]; | |
String s = String.valueOf(ob); | |
return s; | |
} | |
public static void main(String[] args) throws Exception { | |
String data = "562742098461008807900199"; | |
String key = "HZsn43%Y6Z5wyMqp@I&g&u0dl@Vd^oHS";// </dev/urandom tr -dc 'a-zA-Z0-9!@#$%^&*()'|fold -w 32|head -n1 | |
System.out.println(SignTools.sign(data,key)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment