Loading…

Kryptel/Java

Example of File Hashing

Hashing File Contents

This example obtains the list of available hash functions, hashes the contents of the specified file, and prints the computed digests.

import static com.kryptel.Constants.TYPE_HASH_FUNCTION;
import static com.kryptel.Guids.IID_IHashFunction;

import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

import com.kryptel.IKryptelComponent;
import com.kryptel.Loader;
import com.kryptel.hash_function.IHashFunction;

Get the list of available hash functions, instantiate them, and start hashing:

public static void main(String[] args) {
  try {
    UUID[] hfList = Loader.GetComponentList(TYPE_HASH_FUNCTION);
    IKryptelComponent[] hfComp = new IKryptelComponent [hfList.length];
    IHashFunction[] hashFunc = new IHashFunction [hfList.length];

    for (int i = 0; i <  hfList.length; i++) {
      hfComp[i] = (IKryptelComponent)Loader.CreateComponent(hfList[i]);
      hashFunc[i] = (IHashFunction)hfComp[i].GetInterface(IID_IHashFunction);
      hashFunc[i].Init();
    }

Prepare the file for reading:

    String fileName = args[0];

    File f = new File(fileName);
    assert (f.isFile());
    long fsize = f.length();

    byte[] ioBuffer = new byte [64 * 1024];
    int len;

Main loop:

    try (FileInputStream fin = new FileInputStream(fileName)) {
      while (fsize > 0) {
        len = (int)Math.min(fsize, ioBuffer.length);
        fin.read(ioBuffer, 0, len);

        for (int i = 0; i <  hfList.length; i++)
          hashFunc[i].Hash(ioBuffer, 0, len);

        fsize -= len;
      }
    }

Get and print the digests, finish processing:

    byte [] hash;

    for (int i = 0; i <  hfList.length; i++) {
      hash = hashFunc[i].Done();
      System.out.print(hfComp[i].ComponentName());
      System.out.print("\t");
      for (int j = 0; j < hash.length; j++) System.out.printf("%02x", hash[j]);
      System.out.println();
    }
  }
  catch (Exception ex) {
    System.out.println(ex.toString());
  }
}

Hash function interface used: IHashFunction.

More about components: Components, Loader class, IKryptelComponent interface.