Calculating a File Hash

Some time ago a colleague presented me the task of computing a SHA256 hash for an output file. This hash would be stored in a table in a hexadecimal string format, along with the file info, to ensure that the file wasn’t modified by any external sources.

To complete this task I generated the following code that uses CLRInterop to access the .Net System.Security.Cryptography namespace to compute the hash. The returned Byte Array is then converted into an X++ List object by utilizing an example I presented in another post named CLR Array to AX List. This List is then converted into a hexadecimal string.

static str getSHA256FileHash(FileName fileName)
    System.Security.Cryptography.SHA256Managed hash;
    CLRObject bytes, mode, access;
    System.IO.FileStream reader;
    List list;
    ListEnumerator enumer;
    int i, tmp, cnt;
    str s;
    new InteropPermission(InteropKind::ClrInterop).assert();
    try {
        mode    =  CLRInterop::parseClrEnum('System.IO.FileMode','Open');
        access  =  CLRInterop::parseClrEnum('System.IO.FileAccess','Read');
        reader  = new CLRObject('System.IO.FileStream', filename, mode, access);
        hash    = new System.Security.Cryptography.SHA256Managed();
        bytes   = hash.ComputeHash(reader);

        list    = CLRArrayToList(bytes,Types::Integer);
        enumer  = list.getEnumerator();
            s += int2hex(enumer.current(),2);
    } catch { 
        s = '';
    return s;

This code led to the creation of a class that encapsulates several different hash algorithms. The class allows the user to access both the actual List of bytes as well as the hexadecimal string form of the computed hash.

You can instantiate a new instance of the class with the file path and then retrieve the desired hash from the class in the following manner:

slcFileHash    sfh;
List           bytes;
str            hex;
sfh   = new slcFileHash("C:\Temp.txt");
bytes = sfh.MD5_bytes();
hex   = sfh.MD5_str(); 

Or, you can call a method directly from the instantiated class:

str    hex = new slcFileHash("C:\Temp.txt").SHA512_str();


This entry was posted in AX 4.0, Microsoft Dynamics AX and tagged , , , , , . Bookmark the permalink.