HMACSHA 1暗号化
1221 ワード
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class HMACSHA1 {
public static String getHMACSHA1(String base, String key) {
String result = "";
String type = "HmacSHA1";
SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
try {
Mac mac = Mac.getInstance(type);
mac.init(secret);
byte[] digest = mac.doFinal(base.getBytes());
StringBuilder sb=new StringBuilder();
for(byte b:digest){
sb.append(byteToString(b));
}
result = sb.toString();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result;
}
private static String byteToString(byte ib){
char[] Digit={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
char[] ob=new char[2];
ob[0]=Digit[(ib>>>4)& 0X0f];
ob[1]=Digit[ib & 0X0F];
String s=new String(ob);
return s;
}
}