1.废话不多说,直接贴代码
/**
*导包 begin
*/
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
*导包 end
*/
String appSecret="APP密钥";
String plainText="待签名字符串";
final SecretKeySpec secretKeySpec = new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA1");
final Mac hmac = Mac.getInstance("HmacSHA1");
hmac.init(secretKeySpec);
byte[] encode = hmac.doFinal(plainText.getBytes("UTF-8"));
String hash = byteArrayToHex(encode);
String baseStr = new String(Base64.encodeBase64(hash.getBytes()));
// baseStr就是签名后结果啦
private static String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for (byte b : a)
sb.append(String.format("%02x", b & 0xff));
return sb.toString();
}