Algorithm for HashMac


Lastly, we are :



package com.kartik;



 import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

import java.io.UnsupportedEncodingException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

/**

 * This method Genearating HMAC MD5/SH1/SH2....SH256  algo    

 * @author kartik

 * Blog java2blogs.blogspot.com

 * This method Genearating HMAC MD5/SH1/SH2....SH256  algo

 */

public class HashMAC {

   public static void main(String[] args) throws Exception {

//Change this string Value to any other string value what you need

   String stringVal="The quick brown fox jumps over the lazy dog";

 //Change this string key Value to any other string key value what you need

   String key="KAR1043TIK4301MAN1043DAL4301";

//Change this algorithm to any other algorithm like HmacSHA1,HmacSHA64,HmacSHA256,HmacSHA512,MD5

   String algorithm="HmacSHA1";

   String oneWayHashing=hmacDigest(stringVal,key,algorithm);

   System.out.println("After encryption the value is "+oneWayHashing);

  }

/**

 * @purpose This is one way hashing so only encryption no decryption.

 * @param msg msg

 * @param keyString keyString

 * @param algo algo

 * @return digest as a String value.

 */

  public static String hmacDigest(String msg, String keyString, String algo) {

    String digest = null;

    try {

      SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo);

      Mac mac = Mac.getInstance(algo);

      mac.init(key);



       byte[] bytes = mac.doFinal(msg.getBytes("ASCII"));



       StringBuffer hash = new StringBuffer();

      for (int i = 0; i < bytes.length; i++) {

        String hex = Integer.toHexString(0xFF & bytes[i]);

        if (hex.length() == 1) {

          hash.append('0');

        }

        hash.append(hex);

      }

      digest = hash.toString();

    } catch (UnsupportedEncodingException e) {

    } catch (InvalidKeyException e) {

    } catch (NoSuchAlgorithmException e) {

    }

    return digest;

  }

}
Similar we can use other algo which is required for you problem statement.
 For refrence HmacSHA1HmacSHA256HmacSHA512 algos.

Note

Description:

This is one way hashing algorithms means only encryption no decryption. so you need to pass your plain text what you do the encrypted and salt like as key and algo are different type that mention in given below:



HmacSHA1
HmacSHA64
HmacSHA256
HmacSHA512
MD5 






Example 1 One way hashing algorithms:





Oldest

2 comments

Click here for comments
Unknown
admin
24 February 2015 at 02:49 ×

Helpful code. Demonstrate the ability of Kartik. Looking forward for more such piece of code

Reply
avatar
2 March 2015 at 06:18 ×

Thanks boss what you need exactly tell me?
I will try for my level best

Reply
avatar