Android HmacSHA256 Create encryptHMAC(String data, String secret)

Here you can find the source of encryptHMAC(String data, String secret)

Description

encrypt HMAC

Declaration

private static byte[] encryptHMAC(String data, String secret)
            throws IOException 

Method Source Code

//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;

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

public class Main {
    private static byte[] encryptHMAC(String data, String secret)
            throws IOException {
        byte[] bytes = null;
        try {/*  w  w w.  j a  va2 s  .com*/
            SecretKey secretKey = new SecretKeySpec(
                    secret.getBytes("UTF-8"), "HmacMD5");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(data.getBytes("UTF-8"));
        } catch (GeneralSecurityException gse) {
            String msg = getStringFromException(gse);
            throw new IOException(msg);
        }
        return bytes;
    }

    private static String getStringFromException(Throwable e) {
        String result = "";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);
        e.printStackTrace(ps);
        try {
            result = bos.toString("UTF-8");
        } catch (UnsupportedEncodingException e1) {
            // won't happen
        }
        return result;
    }
}

Related

  1. getHmacSha256Base64(String key, String data)
  2. hmacSha1(String str, String keyString)