| How To's / Compute a hash value from a 4GL string | |
This program creates a simple XML document with the string to hash as text of the root node called ROOT.
Then uses the security.Digest API to compute a XML digital signature for the content of the root node, or in other words the string you wish to hash, using a XPath expression.
And finally, retrieves the hash value from the signature and returns it.
IMPORT SECURITY
MAIN
DEFINE result STRING
IF NUM_ARGS() != 2 THEN
DISPLAY "Usage: ComputeHash <string> <hashcode>"
DISPLAY " string: the string to digest"
DISPLAY " hashcode: SHA1, SHA512, SHA384, SHA256, SHA224, MD5"
ELSE
LET result = ComputeHash(ARG_VAL(1), ARG_VAL(2))
IF result IS NOT NULL THEN
DISPLAY "Hash value is: ",result
ELSE
DISPLAY "Error"
END IF
END IF
END MAIN
FUNCTION ComputeHash(toDigest, algo)
DEFINE toDigest, algo, result STRING
DEFINE dgst security.Digest
TRY
LET dgst = security.Digest.CreateDigest(algo)
CALL dgst.AddStringData(toDigest)
LET result = dgst.DoBase64Digest()
CATCH
DISPLAY "ERROR : ", STATUS, " - ", SQLCA.SQLERRM
EXIT PROGRAM(-1)
END TRY
RETURN result
END FUNCTION
Example of usage:
$ fglrun ComputeHash "Hello, world !!!" SHA1
$ Hash value is: Ck1VqNd45QIvq3AZd8XYQLvEhtA=