Monday, October 9

AX 2012 - Calculating the hash Value of a string in X++ code

There is infinite number of ways how to compute a hash and, of course, different implementations and different hash algorithms have different properties. Below code is the most simplest code for generating a hash value of a string in SHA-256. you can update this code and provide your own hashing algorithm by editing the below line with the list of available hashing algorithm in MSDN.

System.Security.Cryptography.SHA512::Create();



Hashing Function:

public str CalculateHash(str tb)
{

    str s;
    ClrObject obj;
    ClrObject SHA256;
    System.Text.StringBuilder sBuilder;
    ClrObject clrStr;
    ClrObject clrStrObject;
    System.Exception clrException;
    System.Array resultByteArray;
    int i;
    int arrayLength ;
    InteropPermission perm;

    perm = new InteropPermission(InteropKind::ClrInterop);
    perm.assert();
    try
    {
        obj = System.Text.Encoding::get_ASCII().GetBytes(tb);
        SHA256 = System.Security.Cryptography.SHA512::Create();
        resultByteArray = SHA256.ComputeHash(obj);
        //BP deviation documented
        sBuilder = new System.Text.StringBuilder();
        arrayLength = resultByteArray.get_Length() ;
        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
        for (i = 0; i <arrayLength; i++)
        {
            clrStrObject = resultByteArray.GetValue(i);
            clrStr = clrStrObject.ToString('x2');
            sBuilder.Append(clrStr);
        }

        // Return the hexadecimal string.
        s = sBuilder.ToString();
    }
    catch (Exception::CLRError)
    {
        //BP deviation documented
        clrException = CLRInterop::getLastException();
        s = clrException.get_Message();
        error(s);
        throw error("@SYS106158");
    }

    CodeAccessPermission::revertAssert();
    return s;

}

No comments:

Post a Comment

Popular Posts