Java tutorial
/* * Computoser is a music-composition algorithm and a website to present the results * Copyright (C) 2012-2014 Bozhidar Bozhanov * * Computoser is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Computoser 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Computoser. If not, see <http://www.gnu.org/licenses/>. */ package com.music.util; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.StringUtils; public final class SecurityUtils { private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; /** * Calculates a HmacSHA1 value * * @param data * @param key * @return HmacSHA1 */ public static String hmac(String data, String key) { try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); String result = new String(Hex.encodeHex(rawHmac)); return result.toUpperCase(); } catch (Exception ex) { throw new RuntimeException("Problem with calculating hmac", ex); } } public static void main(String[] args) { System.out.println(hmac(StringUtils.leftPad("5", 10, '0'), "zonUgkO8FxaPbVfESWZhfzCB")); } }