开发者

Comparing hash from string against hash of local file

What I am trying to do is read from a text file where each line has the 开发者_如何学Pythonpath to a file and then space for a separator and a hash that accompanies it. So I call checkVersion() and loadStrings(File f_) returns a String[], one place for each line. When I try to check the hashes however I end up with something that isn't even hex and is twice as long as it should be, it's probably something obvious that my eyes are just overlooking. The idea behind this is an auto-update for my game to save bandwidth, thanks for your time.

The code is fixed, here is the final version if anyone else has this issue, thanks a lot everyone.

void checkVersion() {
  String[] v = loadStrings("version.txt");
  for(int i=0; i<v.length; i++) {
    String[] piece = split(v[i], " ");  //BREAKS INTO FILENAME, HASH
    println("Checking "+piece[0]+"..."+piece[1]);

    if(checkHash(piece[0], piece[1])) {
      println("ok!");
    } else {
      println("NOT OKAY!");
      //CONTINUE TO DOWNLOAD FILE AND THEN CALL CHECKVERSION AGAIN
    }
  }
}

boolean checkHash(String path_, String hash_) {
  return createHash(path_).equals(hash_);
}

byte[] messageDigest(String message, String algorithm) {
  try {
  java.security.MessageDigest md = java.security.MessageDigest.getInstance(algorithm);
  md.update(message.getBytes());
  return md.digest();
  } catch(java.security.NoSuchAlgorithmException e) {
    println(e.getMessage());
    return null;
  }
} 

String createHash(String path_) {
  byte[] md5hash = messageDigest(new String(loadBytes(path_)),"MD5");
  BigInteger bigInt = new BigInteger(1, md5hash);
  return bigInt.toString(16);
}


The String.getBytes() method returns the bytes that represent the character encodings for the string. It doesn't parse it into bytes that represent a number in some arbitrary radix. For example "AA".getBytes() would yield you 0x41 0x41 on windows, not 10101010b, which is what it appears you were expecting? To get that you could, for example Byte.parseByte("AA", 16)

The library you're using to create hashes probably has a method for taking back in its own string representation. How to convert back depends on the representation, which you didn't give us.


use following code to convert hash bytes to string

//byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
String output = bigInt.toString(16);
System.out.println("MD5: " + output);

for more information

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜