依靠bouncycastle jar实现HMACSHA256加密
在pom.xml添加
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.49</version>
</dependency>
Demo
import java.io.IOException;
import java.security.Security;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import org.apache.http.ParseException;
import org.bouncycastle.crypto.RuntimeCryptoException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class HMACSHA256 {
/**
*
* @param content 加密内容
* @param secret 加密key
* @return
*/
public static String encrytSHA256(String content, String secret) {
try {
Security.addProvider(new BouncyCastleProvider());
SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF8"), "HmacSHA256");
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
byte[] digest = mac.doFinal(content.getBytes("UTF-8"));
return new HexBinaryAdapter().marshal(digest).toLowerCase();
// .toLowerCase()小写
// .toUpperCase();大写
} catch (Exception e) {
throw new RuntimeCryptoException("加密异常");
}
}
public static void main(String[] args) throws ParseException, IOException {
System.out.println(encrytSHA256("加密内容", "key"));
}
}