import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Main { public static void main(String[] args) throws NoSuchAlgorithmException { String input = "Hello world"; MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(input.getBytes()); // convert bytes to hex string StringBuilder hexString = new StringBuilder(); for (byte b : digest) { hexString.append(String.format("%02x", b)); } System.out.println(hexString.toString()); } }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Main { public static void main(String[] args) throws NoSuchAlgorithmException, IOException { File file = new File("example.txt"); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[4096]; int bytesRead; try (FileInputStream fis = new FileInputStream(file)) { while ((bytesRead = fis.read(buffer)) != -1) { md.update(buffer, 0, bytesRead); } } byte[] digest = md.digest(); // convert bytes to hex string StringBuilder hexString = new StringBuilder(); for (byte b : digest) { hexString.append(String.format("%02x", b)); } System.out.println(hexString.toString()); } }In this example, we are generating an MD5 message digest of the contents of a file named "example.txt". We first create a new instance of MessageDigest with the algorithm "MD5". We then read the file using a FileInputStream and update the message digest for each buffer of bytes read. Finally, we call the digest() method to generate the final message digest. To convert the byte array to a readable hex string, we use a StringBuilder and the Formatter class.