Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. import java.lang.Math;
  2. import javax.crypto.Mac;
  3. import javax.crypto.spec.SecretKeySpec;
  4.  
  5.  
  6. // one class needs to have a main() method
  7. public class HelloWorld
  8. {
  9. // arguments are passed using the text field below this editor
  10. public static void main(String[] args)
  11. {
  12. System.out.print(encode("salt", "john"));
  13.  
  14. }
  15.  
  16. public static String encode(String key, String data) {
  17. try {
  18. Mac hmac = Mac.getInstance("HmacSHA256");
  19. SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
  20. hmac.init(secret_key);
  21. return new String(toHexString(hmac.doFinal(data.getBytes("UTF-8"))));
  22. } catch (Exception e) {
  23. throw new RuntimeException(e);
  24. }
  25. }
  26.  
  27.  
  28. public static String toHexString(byte[] ba) {
  29. StringBuilder str = new StringBuilder();
  30. for (int i = 0; i < ba.length; i++) {
  31. String hex = Integer.toHexString(0xFF & ba[i]);
  32. if (hex.length() == 1) {
  33. str.append('0');
  34. }
  35. str.append(String.format("%x", ba[i]));
  36. }
  37. return str.toString();
  38. }
  39.  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement