How to create checksum of a file?





To generate a hash or checksum of a file, below is the implementation shows how do we need to read a file’s bytes in chunks and calculate the checksum.

Code:

public String getFileChecksum(MessageDigest digest, File filethrows IOException
            {
                //passing file to get FileInputStream
                FileInputStream fis = new FileInputStream(file);
                
                //create a byte array to read file content in bytes
                byte[] byteArray = new byte[1024];
                int bytesCount = 0;
                 
                //read the bytes of a file to update the message digest function of MD5 algorithm
                while ((bytesCount = fis.read(byteArray)) != -1) {
                    digest.update(byteArray, 0, bytesCount);
                };
                
                //close the stream
                fis.close();
                
                //get the checksum bytes
                byte[] bytes = digest.digest();
                
                //the bytes are in decimal format & convert them to hexadecimal
                StringBuilder sb = new StringBuilder();
                for(int i=0; ibytes.length ;i++)
                {
                    sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
                }
                
                //return complete checksum value
               return sb.toString();
            }


We can also use above method like below to generate MD5 checksum :
       //Create checksum for this file
            File file = new File("c:/temp/testFile.txt");
             
            //create instance of MD5 algorithm
            MessageDigest md5Digest = MessageDigest.getInstance("MD5");
             
            //Get the hash/checksum
            String hash = getFileHash(md5Digest, file);
             
            //see checksum
            System.out.println(hash);



No comments:

Post a Comment

Fixing yum command on linux

You may find yourself having to fix more packages. So you can just remove everything you had installed via  pip and reinstall everythin...