get Hmac Sha Hex - Android java.security

Android examples for java.security:HMAC

Description

get Hmac Sha Hex

Demo Code


//package com.java2s;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    /**// w  w w  .j  av a  2  s. c  o  m
     * UTF-8
     */
    public static final String UTF_8 = "UTF-8";

    /**
     * 
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    public static String getHmacSha1Hex(String content, String key)
            throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8),
                "HmacSHA1");
        Mac mac = Mac.getInstance(signingKey.getAlgorithm());
        mac.init(signingKey);
        return bytesToHexString(mac.doFinal(content.getBytes(UTF_8)));
    }

    public static String bytesToHexString(byte[] bytes) {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < bytes.length; ++i) {
            int v = bytes[i] & 0xff;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}

Related Tutorials