Android HmacSHA256 Create hmacSha1(String str, String keyString)

Here you can find the source of hmacSha1(String str, String keyString)

Description

hmac Sha

License

Apache License

Declaration

public static String hmacSha1(String str, String keyString) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.security.InvalidKeyException;

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

public class Main {
    private static final char[] hexDigits = "0123456789abcdef"
            .toCharArray();// w w w  .  j  a v a 2 s  . c  om

    public static String hmacSha1(String str, String keyString) {
        final byte[] keyBytes = keyString.getBytes();
        try {
            SecretKey key = new SecretKeySpec(keyBytes, "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(key);
            final byte[] sbs = str.getBytes();
            byte[] result = mac.doFinal(sbs);
            return toHex(result);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            return null;
        }

    }

    public static final String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(2 * bytes.length);
        for (byte b : bytes) {
            sb.append(hexDigits[(b >> 4) & 0xf]).append(hexDigits[b & 0xf]);
        }
        return sb.toString();
    }
}

Related

  1. getHmacSha256Base64(String key, String data)
  2. encryptHMAC(String data, String secret)