简体   繁体   English

如何在Java中计算Torrent文件的哈希信息?

[英]How to calculate hash info for a torrent file in java?

I am building up a project based on p2p networking. 我正在建立一个基于p2p网络的项目。 And I am not able to find any algorithm to calculate hash info for a torrent file. 而且我找不到用于计算种子文件的哈希信息的任何算法。 Can someone please help with the this? 有人可以帮忙吗?

You can use java.security.MessageDigest. 您可以使用java.security.MessageDigest。 Check the below program which calculates MD5Sum/hash bytes and converts it to Hex String format. 检查以下程序,该程序计算MD5Sum / hash字节并将其转换为十六进制字符串格式。

    MessageDigest md5 = null;
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    String md5ChkSumHex = null;
    InputStream is = null;

   String filePath = "D:/myFile.txt";

    try 
    {
        is = new FileInputStream(new File(filePath));

        md5 = MessageDigest.getInstance("MD5");

        try {
            while ((bytesRead = is.read(buffer)) > 0) {
                md5.update(buffer, 0, bytesRead);
            }
        } catch (IOException e) {

            e.printStackTrace();
        }

        byte[] md5ChkSumBytes = md5.digest();

        StringBuffer sb = new StringBuffer();

        /*Convert to hex*/

       for (int j = 0; j < md5ChkSumBytes.length; j++) 
        {
            String hex = Integer.toHexString(
                    (md5ChkSumBytes[j] & 0xff | 0x100)).substring(1, 3);
            sb.append(hex);
        }

        md5ChkSumHex = sb.toString();


    } catch (Exception nsae) {

    }

    return md5ChkSumHex;

There are many algorithms to find hash. 查找哈希的算法很多。 Among them MD5 and SHA1 are popular algorithms. 其中MD5和SHA1是流行的算法。

In the above post, he mentioned the usage of MD5 Hasing. 在以上文章中,他提到了MD5 Hasing的用法。 To do the SHA1 hasing, please use this post . 要完成SHA1的任务,请使用此帖子

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

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