简体   繁体   中英

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

I am building up a project based on p2p networking. 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. Check the below program which calculates MD5Sum/hash bytes and converts it to Hex String format.

    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.

In the above post, he mentioned the usage of MD5 Hasing. To do the SHA1 hasing, please use this post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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