Purvil Bambharolia
Purvil Bambharolia

Reputation: 681

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?

Upvotes: 0

Views: 531

Answers (2)

Santhosh Tangudu
Santhosh Tangudu

Reputation: 787

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.

Upvotes: 0

Roshith
Roshith

Reputation: 2175

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;

Upvotes: 1

Related Questions