使用HmacSHA1哈希运算消息认证码
主要用于两端知道同一个秘钥,通过该秘钥进行消息数据认证
private static final String HMAC_SHA1 = "HmacSHA1";/*** * @param data 数据* @param key 秘钥* @return 密文* @throws NoSuchAlgorithmException* @throws InvalidKeyException*/private static String encrypt(String data, String key) throws NoSuchAlgorithmException, InvalidKeyException {SecretKeySpec secret = new SecretKeySpec(key.getBytes(), HMAC_SHA1);Mac mac = Mac.getInstance(HMAC_SHA1);mac.init(secret);return toHexString(mac.doFinal(data.getBytes()));}private static String toHexString(byte[] bytes) {Formatter formatter = new Formatter();for (byte b : bytes) {formatter.format("%02x", b);}return formatter.toString();}public static void main(String[] args) throws Exception {String hmac = encrypt("This is plaintext", "123");System.out.println(hmac);}
如果觉得《java 实现HMAC-SHA1加密算法》对你有帮助,请点赞、收藏,并留下你的观点哦!