Java HMAC hmacHex(String keyString, String message, String hmac)

Here you can find the source of hmacHex(String keyString, String message, String hmac)

Description

hmac Hex

License

Open Source License

Declaration

protected static String hmacHex(String keyString, String message,
            String hmac) 

Method Source Code

//package com.java2s;
/*/* w  ww. j a  va  2s. co  m*/
 *  Copyright (c) 2011-2015 The original author or authors
 *
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  and Apache License v2.0 which accompanies this distribution.
 *
 *       The Eclipse Public License is available at
 *       http://www.eclipse.org/legal/epl-v10.html
 *
 *       The Apache License v2.0 is available at
 *       http://www.opensource.org/licenses/apache2.0.php
 *
 *  You may elect to redistribute this code under either of these licenses.
 */

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class Main {
    protected static String hmacHex(String keyString, String message,
            String hmac) {
        try {
            SecretKey key = new SecretKeySpec(keyString.getBytes("UTF-8"),
                    hmac);
            Mac mac = Mac.getInstance(key.getAlgorithm());
            mac.init(key);
            return encodeHex(mac.doFinal(message.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException
                | InvalidKeyException e) {
            // doesn't happen, auth will fail in that case
            return "";
        }
    }

    /**
     * @param outBytes
     * @return
     */
    protected static String encodeHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            final int v = ((int) b) & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString();
    }
}

Related

  1. HMAC(String username, BigInteger nonce, String hashedPassword)
  2. hmac_sha(String crypto, byte[] keyBytes, byte[] text)
  3. hmac_sha(String crypto, byte[] keyBytes, byte[] text)
  4. hmacDigest(String message, String secretKey, String algorithm)
  5. hmacEncode(String algorithm, String input, String privateKey)
  6. hmacSha(byte[] keyBytes, byte[] text)
  7. hmacSha(String crypto, String key, String value)
  8. hmacSha1(byte[] data, byte[] key)
  9. hmacSha1(byte[] key_bytes, byte[] text_bytes)