简体   繁体   English

如何在Java游戏中检查MD5资源的哈希值是否正确?

[英]How do I check if MD5 hashes of resources are correct in Java game?

I am developing a Java game and I want to verify that the resources are not different from the ones I included. 我正在开发Java游戏,我想验证资源与我包含的资源没有不同。 Can I do this by checking the MD5 hash and if I can how? 我可以通过检查MD5哈希来做到这一点吗? Any help is appreciated, thank you. 任何帮助表示赞赏,谢谢。

The code to get MD5 was found here :. 这里找到获取MD5的代码: I just modified to accept the path to resource and read the bytes of that resource into a byte array which is then passed to the MD5 algorithm 我刚刚修改为接受资源路径,并将该资源的字节读入字节数组,然后将其传递给MD5算法

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

    public static String getMD5(String pathToResource) {
            Path path = Paths.get(pathToResource);
            byte[] data = Files.readAllBytes(path);
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] messageDigest = md.digest(data);
                BigInteger number = new BigInteger(1, messageDigest);
                String hashtext = number.toString(16);
                // Now we need to zero pad it if you actually want the full 32 chars.
                while (hashtext.length() < 32) {
                    hashtext = "0" + hashtext;
                }
                return hashtext;
            }
            catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM