Java tutorial
//package com.java2s; /** * Copyright (C) 2014-2016 Regents of the University of California. * @author: Jeff Thompson <jefft0@remap.ucla.edu> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * A copy of the GNU Lesser General Public License is in the file COPYING. */ import java.nio.ByteBuffer; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class Main { /** * Compute the HMAC with SHA-256 of data, as defined in * http://tools.ietf.org/html/rfc2104#section-2 . * @param key The key byte array. * @param data The input byte buffer. This does not change the position. * @return The HMAC result. */ public static byte[] computeHmacWithSha256(byte[] key, ByteBuffer data) { final String algorithm = "HmacSHA256"; Mac mac; try { mac = Mac.getInstance(algorithm); } catch (NoSuchAlgorithmException ex) { // Don't expect this to happen. throw new Error("computeHmac: " + algorithm + " is not supported: " + ex.getMessage()); } try { mac.init(new SecretKeySpec(key, algorithm)); } catch (InvalidKeyException ex) { // Don't expect this to happen. throw new Error("computeHmac: Can't init " + algorithm + " with key: " + ex.getMessage()); } int savePosition = data.position(); mac.update(data); data.position(savePosition); return mac.doFinal(); } }