Skip to main content

Problem:

The SHA1 is a standard hashing algorithm that given a sting of bytes will produce a hash code for the string. Any changes to the string would result in a very different hash code so it can be used to ensure a message has not been tampered with.

How you use this algorithm in .Net COBOL ?

Resolution:

The .Net Framework contains an implementation the SHA1 algorithm.  You can use these classes from COBOL.

An example project that does this is attached to this RPI.

The program code is:-

      $set sourceformat"variable"

       program-id. HashIt as "SHA1Hash.Hashit".

       environment division.

       configuration section.

       repository.

           class cSHA1Managed as "System.Security.Cryptography.SHA1Managed"

           class cStringBuilder as "System.Text.StringBuilder"

           .

       data division.

       working-storage section.

       01  mymessage               pic x(22)   value "This is a TEST String.".

       01  mySHA1                  cSHA1Managed.

       01  myByteArray             binary-char unsigned occurs any. *> Byte Array

       01  myHash                  binary-char unsigned occurs any. *> Byte Array

       01  ws-byte                 binary-char unsigned. *> Byte

       

       01  strBuilder              cStringBuilder.

       01  array-len               binary-long.

       

       

       procedure division.

       

      ***** Create a SHA1 Hashing Instance

       

           set mySHA1 to cSHA1Managed::"New"()

           

           set myByteArray to mymessage

           set myHash to mySHA1::"ComputeHash"(myByteArray)

           

      ***** Now output a hex representation of the SHA1 Hash

       

           perform create-hex-string

           display "Message=" mymessage

           display "SHA1 Hash Code=" strBuilder

           goback.

           

       create-hex-string section.

      ******************************************       

      * Create Hex String from Byte[]

      ******************************************       

       

           set strBuilder to cStringBuilder::"New"()

           set array-len to myHash::"Length"

           move length of myHash to array-len

           

           perform varying ws-byte through myHash

           

               invoke strBuilder::"Append"(String::"Format"("{0,2:x}", ws-byte)::"Replace"(" " , "0"))   

           

           end-perform

           .

       

       

       end program HashIt.

Old KB# 1353