20
Sat, Apr
5 New Articles

The API Corner: Verifying That Nothing Has Changed, Part 2

APIs
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Explore more options with the Calculate Hash API.

 

Last month, in Verifying That Nothing Has Changed, we saw how easy it can be to create a hash over a string such as 'Some data to be hashed' by using the Calculate Hash API. We also saw how the calculated hash value is very dependent on what data is being hashed. Something as simple as a trailing blank or a punctuation change can cause significant changes in the derived hash value. Today, we'll look at some options on how we can hash data, and we'll see that agreement between the generator and verifier of the hash value on the how is not nearly as important as the what.

Last month's DOHASH program hashed the left-adjusted 25-byte string 'Some data to be hashed   ' using one call to the Calculate Hash API and got back the corresponding hash value. For longer stringsfor instance, a string representing all of the records in a fileit might be more convenient (and in some cases required due to high-level language constraints) to pass the data to be hashed in pieces (records if you will) using multiple API calls and, when all of the data has been processed, then get back the final hash value.

To demonstrate this piecemeal approach to hashing, we'll continue to hash the string 'Some data to be hashed   ' but we'll do it passing only 5 bytes of the string per call to the Calculate Hash API. That is, on the first call we'll hash 'Some ' (note that there's a trailing blank after the 'e' of Some), the second call 'data ', the third call 'to be', and so on. The program to accomplish this is shown below.

h dftactgrp(*no)                                                          

                                                                          

d CrtAlgCtx       pr                 extproc('Qc3CreateAlgorithmContext')

d AlgDsc                     4096a   const options(*varsize)              

d FmtAlgDsc                    8a   const                                

d AlgCtxTkn                     8a                                        

d ErrCde                             likeds(QUSEC)                        

                                                                            

d DltAlgCtx       pr                 extproc('Qc3DestroyAlgorithmContext')

d AlgCtxTkn                     8a   const                                

d ErrCde                             likeds(QUSEC)                        

                                                                          

d HshDta         pr                 extproc('Qc3CalculateHash')          

d InpDta                     4096a   const options(*varsize)              

d LenInpDta                   10i 0 const                                

d FmtInpDta                     8a   const                                

d AlgDsc                     4096a   const options(*varsize)              

d FmtAlgDsc                     8a   const                                

d CryptoPrv                     1a   const                                

d CryptoDev                   10a   const                          

d HshVal                       1a   options(*varsize)              

d ErrCde                             likeds(qusec)                  

                                                                    

d Data           s             25a   inz('Some data to be hashed')  

d DataSubset     s             5a                                  

d HashValue       s             32a                                  

d X               s             10i 0                                

                                                                    

/copy qsysinc/qrpglesrc,qc3cci                                      

/copy qsysinc/qrpglesrc,qusec                                      

                                                                    

/free                                                                

                                                                    

QUSBPrv = 0;                                                      

                                                                    

QC3Ha = 3;                                                          

CrtAlgCtx(QC3D0500 :'ALGD0500' :QC3ACT :QUSEC);                    

                                                                    

QC3FOF = '0';                                                      

X = 1;                                                      

                                                              

dow X < %size(Data);                                        

     DataSubset = %subst(Data :X :%size(DataSubset));        

     HshDta(DataSubset :%size(DataSubset) :'DATA0100'        

             :QC3D0100 :'ALGD0100' :'0' :' '                  

             :HashValue :QUSEC);                              

     X += %size(DataSubset);                                  

enddo;                                                      

                                                              

QC3FOF = '1';                                                

HshDta(' ' :0 :'DATA0100'                                    

         :QC3D0100 :'ALGD0100' :'0' :' '                      

         :HashValue :QUSEC);                                  

                                                              

DltAlgCtx(QC3ACT :QUSEC);                                    

                                                              

*inlr = *on;                                                

return;                                                      

                                                              

/end-free  

 

Reviewing the previous code, you'll find that two new APIs are being used. The first new API, Create Algorithm Context, can be used to create a job-specific context (environment) to enable the sharing of algorithmic parameters and interim values across multiple API calls. The API has four parameters:

  1. Algorithm description (AlgDsc)The algorithm and related parameters to be used within this context
  2. Algorithm description format name (FmtAlgDsc)The format of the Algorithm description (the first parameter). Format ALGD0500, used in this month's program, indicates that the Algorithm description is related to hashing. Other formats are defined for algorithms such as block cipher, stream cipher, and public keys.
  3. Algorithm context token (AlgCtxTkn)The output parameter to receive an 8-byte token that uniquely identifies the context being created. The format of a token is not defined. The token value is simply passed as-is in subsequent calls to other APIs in order to identify the algorithmic environment to be used.
  4. Error code (ErrCde)The standard API error code parameter

Notice that when calling the Create Algorithm Context API, the first and second parameters being passed are using the same values as the fourth and fifth parameters used last month when calling the Calculate Hash API. Combined, these two parameters, the data structure QC3D0500, and the constant 'ALGD0500' indicate that the program will be performing SHA-256 hashing. By using these values with the Create Algorithm Context API, we are simply enabling the ability to do the actual hashing using one or more calls to the Calculate Hash API.

Having created the hashing context, the program then sets the Final operation flag variable (QC3FOF) of the QSYSINC QC3CCI provided data structure QC3D0100 to the value '0'. When subsequently calling the Calculate Hash API, a Final operation flag value of '0' indicates that the hashing operation is still in progress, allowing us to continue calling the API with additional data to be included in the hashing operation.

The program then enters a DOW conditioned by not all data of the string to be hashed having been processed. Within the DOW, the program performs these steps:

  1. Sets the variable DataSubset to the next 5 bytes of the string 'Some data to be' to be hashed.
  2. Calls the Calculate Hash API to hash the currently identified 5 bytes. In addition to the change from last month's program regarding the number of bytes to hash (25 to 5), this call to the API also uses different values for the fourth and fifth parameters. Last month's call to the Calculate Hash API set these parameters, respectively, to the data structure QC3D0500 and format 'ALGD0500' in order to provide the necessary parameters for the hashing algorithm to be used. This month, the hashing algorithm parameters are set when calling the Create Algorithm Context API, so the fourth and fifth parameters are set to the data structure QC3D0100 and format 'ALGD0100', respectively, in order to reference the previously created algorithm context the program wants to work with.
  3. Identifies the next 5 bytes to be hashed.
  4. Re-runs the DOW until all data has been hashed.

When all of the string has been hashed, the DOW ends, the variable QC3FOF is set to the value '1' (indicating that the hashing operation is complete), and the Calculate Hash API is called one last time in order to obtain the hash value for the previously hashed data. On this call to the API, the second parameter, LenInpDta, is set to zero, indicating that no additional data is to be hashed as part of the API processing.

The program can, if desired, avoid this sixth call to the Calculate Hash API. If, within the DOW block, the program can determine that the fifth call to the API represents the last data to be used, then the program can set the QC3FOF variable to the value of '1' on the fifth call and obtain the hash value as an output of this fifth call. In the case of the sample program, this would be easy enough to do as the length of the string to be hashed is known in advance.

In other cases, this determination of the last data to be hashed may not be as straightforward. The current approach, though, is structured in a way that makes it fairly easy to replace the string being hashed (the variable Data) with, for instance, a database file. Prior to entering the DOW issuing a READ to a file, changing the DOW conditioning to test for the file being not %EOF, hashing the record buffer previously read, READing the next record, and re-entering the DOW allows the program to now create a hash value over the contents of the entire filewithout, in advance, having to determine the number of records in the file.

Having completed the hashing operation, the second new API, Destroy Algorithm Context, is called to destroy the context previously created with the Create Algorithm Context API (and subsequently referenced when calling the Calculate Hash API using format ALGD0100). The two parameters passed are the token identifying the context and the standard API error code. The program then ends.

Assuming that the previous program source is stored in member DOHASH2 of source file QRPGLESRC, you can create the program using the command CRTBNDRPG PGM(DOHASH2).

Calling DOHASH2 will then generate the following 32-byte HashValue (shown in hex):

7FCBD451 76B2E190 AFC956AE F507CB35

A9C7F58B 36A68E25 58E9F3F9 736FB213

 

Hopefully, you will notice that, while this hash value was created using multiple calls to Calculate Hash API (five times with data to be hashed, one time to access the hash value), the returned HashValue is the same as last month's hashing of the string with one call. The internal processing related to the data being hashed did not impact the derived hash value.

As usual, if you have any API questions, send them to me at This email address is being protected from spambots. You need JavaScript enabled to view it.

Bruce Vining

Bruce Vining is president and co-founder of Bruce Vining Services, LLC, a firm providing contract programming and consulting services to the System i community. He began his career in 1979 as an IBM Systems Engineer in St. Louis, Missouri, and then transferred to Rochester, Minnesota, in 1985, where he continues to reside. From 1992 until leaving IBM in 2007, Bruce was a member of the System Design Control Group responsible for OS/400 and i5/OS areas such as System APIs, Globalization, and Software Serviceability. He is also the designer of Control Language for Files (CLF).A frequent speaker and writer, Bruce can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it.. 


MC Press books written by Bruce Vining available now on the MC Press Bookstore.

IBM System i APIs at Work IBM System i APIs at Work
Leverage the power of APIs with this definitive resource.
List Price $89.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: