Advertisement
Guest User

how to generate minecraft hex digests in java

a guest
Dec 30th, 2013
1,273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.16 KB | None | 0 0
  1. package com.serverid;
  2.  
  3. import java.io.UnsupportedEncodingException;
  4. import java.security.MessageDigest;
  5. import java.security.NoSuchAlgorithmException;
  6.  
  7. public class ServerID
  8. {
  9.     final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
  10.    
  11.     public static void main(String[] args)
  12.     {
  13.         // The test values provided on http://wiki.vg/Protocol_Encryption are:
  14.         // sha1(Notch) :  4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48
  15.         // sha1(jeb_)  : -7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1
  16.         System.out.println(javaHexDigest("Notch"));
  17.         System.out.println(javaHexDigest("jeb_"));
  18.     }
  19.  
  20.     private static String javaHexDigest(String data)
  21.     {
  22.         MessageDigest digest = null;
  23.           try {
  24.             digest = MessageDigest.getInstance("SHA-1");
  25.             digest.reset();
  26.             digest.update(data.getBytes("UTF-8"));
  27.         } catch (NoSuchAlgorithmException e) {
  28.             e.printStackTrace();
  29.         } catch (UnsupportedEncodingException e) {
  30.             e.printStackTrace();
  31.         }
  32.         byte[] hash = digest.digest();
  33.         boolean negative = (hash[0] & 0x80) == 0x80;
  34.         if (negative)
  35.             hash = twosCompliment(hash);
  36.         String digests = getHexString(hash);
  37.         if (digests.startsWith("0"))
  38.         {
  39.             digests = digests.replaceFirst("0", digests);
  40.         }
  41.         if (negative)
  42.         {
  43.             digests = "-" + digests;
  44.         }
  45.         digests = digests.toLowerCase();
  46.         return digests;
  47.     }
  48.  
  49.     public static String getHexString(byte[] bytes) {
  50.         char[] hexChars = new char[bytes.length * 2];
  51.         int v;
  52.         for ( int j = 0; j < bytes.length; j++ ) {
  53.             v = bytes[j] & 0xFF;
  54.             hexChars[j * 2] = hexArray[v >>> 4];
  55.             hexChars[j * 2 + 1] = hexArray[v & 0x0F];
  56.         }
  57.         return new String(hexChars);
  58.     }
  59.    
  60.     private static byte[] twosCompliment(byte[] p)
  61.     {
  62.         int i;
  63.         boolean carry = true;
  64.         for (i = p.length - 1; i >= 0; i--)
  65.         {
  66.             p[i] = (byte)~p[i];
  67.             if (carry)
  68.             {
  69.                 carry = p[i] == 0xFF;
  70.                 p[i]++;
  71.             }
  72.         }
  73.         return p;
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement