Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement