Created
April 27, 2017 00:13
-
-
Save jl91/f2c469e60b2c5bee323d0239f03421dd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.Math; | |
import javax.crypto.Mac; | |
import javax.crypto.spec.SecretKeySpec; | |
// one class needs to have a main() method | |
public class HelloWorld | |
{ | |
// arguments are passed using the text field below this editor | |
public static void main(String[] args) | |
{ | |
System.out.print(encode("salt", "john")); | |
} | |
public static String encode(String key, String data) { | |
try { | |
Mac hmac = Mac.getInstance("HmacSHA256"); | |
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"); | |
hmac.init(secret_key); | |
return new String(toHexString(hmac.doFinal(data.getBytes("UTF-8")))); | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} | |
public static String toHexString(byte[] ba) { | |
StringBuilder str = new StringBuilder(); | |
for (int i = 0; i < ba.length; i++) { | |
String hex = Integer.toHexString(0xFF & ba[i]); | |
if (hex.length() == 1) { | |
str.append('0'); | |
} | |
str.append(String.format("%x", ba[i])); | |
} | |
return str.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment