Skip to content

Simple hashing | Hash Results

Black_Baroness edited this page Sep 1, 2022 · 1 revision

The last link in the chain is the HashResult. It is an array of bytes that can be turned into something. They can also be compared with each other.

Let's write a small program that takes 2 files and compares them and outputs their SHA256 hash.

public class Example {
    
    private final File firstFile;
    private final File secondFile;

    public Example(File firstFile, File secondFile) {
        this.firstFile = firstFile;
        this.secondFile = secondFile;
    }
    
    public void run() {
        HashAlgorithm algorithm = new Sha().sha256();

        HashResult firstResult = algorithm.hash(HashSources.ofFile(firstFile));
        HashResult secondResult = algorithm.hash(HashSources.ofFile(secondFile));

        System.out.println("First file hash: " + firstResult.string());
        System.out.println("Second file hash: " + secondResult.string());

        System.out.println(firstResult.sameAs(secondResult)
                ? "Files are the same"
                : "Files are not the same"
        );
    }
}
Clone this wiki locally