Skip to content

Instantly share code, notes, and snippets.

@viniciuszago
Last active June 23, 2016 17:46
Show Gist options
  • Save viniciuszago/75a097d90f72293470f1 to your computer and use it in GitHub Desktop.
Save viniciuszago/75a097d90f72293470f1 to your computer and use it in GitHub Desktop.
package controllers;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class DataTransferSign
{
private static String key = "your_key";
private static String merchId = "your_merchID";
public static void main(String[] args) throws Exception
{
String amount = args[0];
String ccy = args[1];
String idno = args[2];
String str = merchId + amount + ccy + idno;
System.out.println(hmacDigest(str, key, "HmacMD5"));
}
public static byte[] hexStringToByteArray(String s)
{
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;
}
public static String hmacDigest(String msg, String keyString, String algo)
{
String digest = null;
try
{
byte[] hexStringToByteArray = hexStringToByteArray(keyString);
SecretKeySpec key = new SecretKeySpec(hexStringToByteArray, 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment