SHA-2 is believe the most secure hashing algorithm as this article is written, here are few examples for the SHA implementation. The possible MessageDigest algorithm are SHA-1, SHA-256, SHA-384, and SHA-512, you can check the reference for the detail.It will use SHA-256 hashing algorithm to generate a checksum for file “c:\\loging.log”.
package org.best.example; import java.io.FileInputStream; import java.security.MessageDigest; public class SHACheckSumExample { public static void main(String[] args)throws Exception { MessageDigest md = MessageDigest.getInstance("SHA-256"); FileInputStream fis = new FileInputStream("c:\\loging.log"); byte[] dataBytes = new byte[1024]; int nread = 0; while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread); }; byte[] mdbytes = md.digest(); //convert the byte to hex format method 1 StringBuffer sb = new StringBuffer(); for (int i = 0; i < mdbytes.length; i++) { sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } System.out.println("Hex format : " + sb.toString()); //convert the byte to hex format method 2 StringBuffer hexString = new StringBuffer(); for (int i=0;i<mdbytes.length;i++) { hexString.append(Integer.toHexString(0xFF & mdbytes[i])); } System.out.println("Hex format : " + hexString.toString()); } }
Output
Hex format : 21a57f2fe765e1ae4a8bf15d73fc1bf2a533f547f2343d12a499d9c0592044d4 Hex format : 21a57f2fe765e1ae4a8bf15d73fc1bf2a533f547f2343d12a499d9c0592044d4
No comments:
Post a Comment