13
Wed, Nov
5 New Articles

Simplify Encryption with the Use of RPG Reusable Procedures

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

Secure your data using encryption/decryption APIs within RPG.

 

The encryption/decryption APIs can be difficult to work with, so let's create some procedures to simplify all of the details of the initialization and data structures. We'll create the functionality that we are really looking for through the simplicity of reuse!

 

With all of the advancements of technology, it is getting easier and easier for users to get access to the data they need. But it is also getting easier for people who you don't want to have access to get to your data. So you have to think about security. In this article, we will discuss how to encrypt and decrypt your data using RPG.

The APIs

Here are the APIs that we will be using to perform the encryption and decryption.

 

APIs for Encryption and Decryption

Description

Original Program Model (OPM)

Integrated Language Environment (ILE)

Encryption

QC3ENCDT

Qc3EncryptData

Decryption

QC3DECDT

QC3DecryptData

 

There are a lot of different ways of providing encryption, and there is quite a bit of configuration to get the APIs working properly. For the purpose of this article, we will be working only with the block cipher algorithms: DES, Triple DES, and AES.

The Prototypes

For our examples, we will use the QC3ENCDT and QC3DECDT API references, because they work in both OPM and ILE environments. The hyperlinks will direct you to the API reference on the IBM Web site for additional information.

 

QC3ENCDT will encrypt the data.

 

     D encryptDataAPI...

     D                 PR                  extPgm('QC3ENCDT')

     D  argIn                     65535    const options(*varsize)

     D  argInLen                     10I 0 const

     D  argInFmt                      8    const

     D  argAlg                    65535    const options(*varsize)

     D  argAlgFmt                     8    const

     D  argKey                    65535    const options(*varsize)

     D  argKeyFmt                     8    const

     D  argCryptoPro                  1    const

     D  argCryptoDev                 10    const

     D  argOut                    65535

     D  argOutBuffLen                10I 0 const

     D  argOutLen                    10I 0

     D  argError                           likeDs(QUSEC)

 

 

QC3DECDT will decrypt the data. The prototype for decryption is the same as for encryption, with the exception of one field. The third field (argInFmt) is omitted for the decryption API.

 

     D decryptDataAPI...

     D                 PR                  extPgm('QC3DECDT')

     D  argIn                     65535    const options(*varsize)

     D  argInLen                     10I 0 const

     D  argAlg                    65535    const options(*varsize)

     D  argAlgFmt                     8    const

     D  argKey                    65535    const options(*varsize)

     D  argKeyFmt                     8    const

     D  argCryptoPro                  1    const

     D  argCryptoDev                 10    const

     D  argOut                    65535

     D  argOutBuffLen                10I 0 const

     D  argOutLen                    10I 0

     D  argError                           likeDs(QUSEC)

 

Cipher Setup

Those encryption and decryption APIs have a lot of parameters! Let's take a walk through them. When we're done, we'll create an initialization procedure to take care of the settings before we start using the APIs.

 

We will specifically be using block algorithm ciphers on a single field. You can click on the API hyperlinks above to find out other configurations that are available. Here are the settings that we will be using to set up for these types of operations.

 

Parameter Settings

 

Parameter

Description

1

argIn

Source data to be encrypted/decrypted.

2

argInLen

Length of the argIn parameter (1).

3

argInFmt

'DATA0100'—Format of input (exclusive to encryption). Defines parameter (1) as a single data field.

4

argAlg

QC3D0200—Algorithm parameters. A data structure in QSYSINC/QRPGLESRC,QC3CCI.

5

argAlgFmt

'ALGD0200'—Indicates a block cipher algorithm.

6

argKey

QC3D020000—Key parameters. (We'll be using a qualified data structure that includes this.)

7

argKeyFmt

'KEYD0200'—Indicates the encryption/decryption key is contained in the argKey parameter (6).

8

argCryptoPro

'0'—Let the system figure out the Cryptographic Service Provider (CSP).

9

argCryptoDev

*BLANKS—No hardware encryption device used.

10

argOut

Resulting output data after encryption/decryption operation.

11

argOutBuffLen

Size of output buffer in argOut parameter (10).

12

argOutLen

The length of the resulting data in the argOut parameter (10).

13

argError

QUSEC—Common error code data structure. (We'll be using a qualified data structure that includes this.)

 

Once we have the values initialized, the only values that will change will be the input and output data and the associated lengths that we are working with. The following procedure can be used to initialize these values:

 

     D cipherSetup...

     D                 PR

     D  argKey                     1024A   const varying

     D                                     options(*varsize)

     D  argAlgorithm                 10I 0 const

 

     D**********************************************************************

     D*  cipherSetup() using Block Cipher Algorithms

     D**********************************************************************

     P cipherSetup...

     P                 B                   EXPORT

     D cipherSetup...

     D                 PI

     D  argKey                     1024A   const varying

     D                                     options(*varsize)

     D  argAlgorithm                 10I 0 const

     D*

     D svBytes         S             52A

      /free

        // Initialize the Algorithm Data Structure QC3D0200

        QC3D0200 = *AllX'00';

        QC3BCA = argAlgorithm;

        select;

          when argAlgorithm = DES;

            QC3BL = 8;

          when argAlgorithm = TRIPLE_DES;

            QC3BL = 8;

          when argAlgorithm = AES;

            // For AES, could be 16, 24 or 32

            QC3BL = 16;

          other;

            QC3BL = 0;

        endsl;

        QC3MODE = '1';

        QC3PO = '1';

        QC3EKS = 0;

        // Initialize the Key Data Structure QC3D020000

        keyDesc.QC3D020000 = *AllX'00';

        keyDesc.QC3D020000.QC3KT = argAlgorithm;

        keyDesc.QC3D020000.QC3KF = '0';

        keyDesc.QC3D020000.QC3KSL = %len(%trim(argKey));

        keyDesc.QC3Key = %trim(argKey);

        // Initialize the Rest of the Parameters

        stdError.QUSEC = *AllX'00';

        stdError.QUSEC.QUSBPRV = 1040;

        cryptoPro = '0';

        cryptoDev = *BLANKS;

      /end-free

     P                 E

 

QC3D0200 is the data structure that sets up the algorithm. We will initially clear out the entire data structure bits with zeros. Then, we can just set the values that we need to:

 

  • QC3BCA uses constants to determine the type of encryption that we will be using: DES, Triple DES, or AES.
  • QC3BL is the block length to be used. For DES and Triple DES, the value must be 8. For AES, you could use 16, 24, or 32. We will be using 16, but you can change that to suit your needs.
  • QC3MODE will be set to '1', indicating the CBC mode.
  • QC3PO will be set to '1', indicating that padding will be used with the character specified in QC3PC, which we will leave as zeros.

 

QC3D020000 is the data structure that sets up the key. We will initially clear out the entire data structure bits with zeros. Then, we can just set the values that we need to:

 

  • QC3KT is the key type, indicating the type of encryption that we will be using: DES, Triple DES, or AES. For the options that we are using, we can reuse the constants used in the QC3BA field of QC3D0200. If you were to use the additional values available, such as 30, 50, or 51, then you would not be able to reuse the codes. But, for simplicity in this example, we were able to.
  • QC3KF is the key format; '0' specifies that the key is a binary value.
  • QC3KSL is the key length.

Extending the IBM Data Structures

I find the code easier to understand if I create qualified data structures to extend the existing IBM data structures to contain character fields that I will be working with.

 

The QUSEC data structure is the IBM-provided common error code data structure to be used with APIs. It can be found in the QSYSINC/QRPGLESRC,QUSEC source file.

 

     D* The QUSEC Source Contains the Common Error Code Data Structure.

     D/COPY QSYSINC/QRPGLESRC,QUSEC

     D stdError        DS                  qualified

     D  QUSEC                              likeDs(QUSEC)

     D  outError                   1024A

 

The QC3D020000 data structure is used for the key description data structure and can be found in the QSYSINC/QRPGLESRC,QC3CCI source file, along with the QC3D0200 data structure. We will be passing in a key that we can add to the end of the existing data structure.

 

     D* The QC3CCI Source Contains Encryption Data Structures.

     D/COPY QSYSINC/QRPGLESRC,QC3CCI

     D keyDesc         DS                  qualified

     D  QC3D020000                         likeDs(QC3D020000)

     D  QC3Key                     1024A

Encapsulating the APIs

We will simplify the use of the encryption APIs by creating custom procedures to handle all of the details.

 

Here are the encryptData prototype and procedure:

 

     D encryptData...

     D                 PR         65535A

     D  argData                   65535A   const varying

     D                                     options(*varsize)

     D  argOutLen                    10I 0

 

 

     D**********************************************************************

     D*  encryptData() using Block Cipher Algorithms

     D**********************************************************************

     P encryptData...

     P                 B                   EXPORT

     D encryptData...

     D                 PI         65535A

     D  argData                   65535A   const varying

     D                                     options(*varsize)

     D  argOutLen                    10I 0

     D*

     D svOutData       S          65535A

     D svBytes         S             52A

      /free

        svOutData = *BLANKS;

        // API

        encryptDataAPI(argData: %len(argData): 'DATA0100':

                    QC3D0200: 'ALGD0200':

                    keyDesc: 'KEYD0200':

                    cryptoPro: cryptoDev:

                    svOutData: %size(svOutData): argOutLen:

                    stdError);

        if stdError.QUSEC.QUSBAVL > 0;

          // Error

          svBytes = 'Error: ' + stdError.QUSEC.QUSEI;

          DSPLY svBytes;

          svOutData = *BLANKS;

        else;

        endif;

        return svOutData;

      /end-free

     P                 E

 

And here are our decryptData prototype and procedure:

 

     D decryptData...

     D                 PR         65535A

     D  argData                   65535A   const varying

     D                                     options(*varsize)

     D  argInLen                     10I 0

 

     D**********************************************************************

     D*  decryptData() using Block Cipher Algorithms

     D**********************************************************************

     P decryptData...

     P                 B                   EXPORT

     D decryptData...

     D                 PI         65535A

     D  argData                   65535A   const varying

     D                                     options(*varsize)

     D  argInLen                     10I 0

     D*

     D svOutData       S          65535A

     D svOutDataLen    S             10I 0

     D svBytes         S             52A

      /free

        svOutData = *BLANKS;

        // API

        decryptDataAPI(argData: argInLen:

                    QC3D0200: 'ALGD0200':

                    keyDesc: 'KEYD0200':

                    cryptoPro: cryptoDev:

                    svOutData: %size(svOutData): svOutDataLen:

                    stdError);

        if stdError.QUSEC.QUSBAVL > 0;

          // Error

          svBytes = 'Error: ' + stdError.QUSEC.QUSEI;

          DSPLY svBytes;

          svOutData = *BLANKS;

        else;

        endif;

        return svOutData;

      /end-free

     P                 E

 

You can see that with the custom procedures, you have only two parameters, which makes the code much easier to work with.

The Code

Now we get to enjoy the fruits or our labor! Let's use our new procedures to encrypt a piece of valuable data and then decrypt it to make sure we get back the same results that we put in.

 

One obvious piece of information you would want to protect would be Social Security numbers. We will use an invalid Social Security number, 987-65-4320, for our example.

 

     D ssn             S            128A

     D results         S          65535A

     D secretKey       S             32A

     D cryptoPro       S              1A

     D cryptoDev       S             10A

     D encryptLen      S             10I 0

     D displayBytes    S             52A

     D************************* Constants *******************************

     D* Block Cipher Algorithms

     D DES             C                   20

     D TRIPLE_DES      C                   21

     D AES             C                   22

     D**************************** Main *********************************

      /free

       ssn = '987654320';

       //------------------------------------------------

       // AES

       //------------------------------------------------

       secretKey = 'MC_pr3$$!0nL1N3_';

       displayBytes = '----- AES ENCRYPTION -----';

       DSPLY displayBytes;

       displayBytes = 'Original: ' + %trim(ssn);

       DSPLY displayBytes;

       // Configure Encryption Cipher

       cipherSetup(secretKey: AES);

       // Encrypt the Data

       results = encryptData(ssn: encryptLen);

       displayBytes = 'Encrypted: ' + %trim(results);

       DSPLY displayBytes;

       // Decrypt the Data

       results = decryptData(results: encryptLen);

       displayBytes = 'Decrypted: ' + %trim(results);

       DSPLY displayBytes;

       //------------------------------------------------

       // Triple DES

       //------------------------------------------------

       secretKey = 'MC_pr3$$';

       displayBytes = '----- TRIPLE DES ENCRYPTION -----';

       DSPLY displayBytes;

       displayBytes = 'Original: ' + %trim(ssn);

       DSPLY displayBytes;

       // Configure Encryption Cipher

       cipherSetup(secretKey: TRIPLE_DES);

       // Encrypt the Data

       results = encryptData(ssn: encryptLen);

       displayBytes = 'Encrypted: ' + %trim(results);

       DSPLY displayBytes;

       // Decrypt the Data

       results = decryptData(results: encryptLen);

       displayBytes = 'Decrypted: ' + %trim(results);

       DSPLY displayBytes;

       *inlr = *ON;

      /end-free

The Output

When you run the program, you will see the following screen:

 

120209TomSnyder_Encryption 

Figure 1: This is the output you get when you run the program.

 

The error code logic in the encryptData and decryptData procedures could come in handy if you have any problems. Just go to the hyperlinks on the API names and look up their meanings to translate the error codes.

Is Your Data Secure?

Now your data is encrypted! But is it safe? Not completely. What if someone were to get at the source code? The key is coded right there, and anyone who can view the source could decrypt the data.

 

You may have a bunch of ideas about how to overcome that obstacle. Maybe you could be creative with how you create your key, but the person reading the code would just be challenged with figuring out your logic. Or maybe you could remove the source from the system and upload it only when you are modifying it. But could someone retrieve the source from the program?

 

Don't fear. There is an answer for that with key stores, but we'll save that topic for another day. This article is the first step to understanding encryption and the resources that are available to you. If we tackle this a piece at a time, total understanding will be much easier.

Download the Code

You can download the code used in this article—as well as the fixed-format version—by clicking here.

 

Happy coding!

Thomas Snyder

Thomas Snyder has a diverse spectrum of programming experience encompassing IBM technologies, open source, Apple, and Microsoft and using these technologies with applications on the server, on the web, or on mobile devices.

Tom has more than 20 years' experience as a software developer in various environments, primarily in RPG, Java, C#, and PHP. He holds certifications in Java from Sun and PHP from Zend. Prior to software development, Tom worked as a hardware engineer at Intel. He is a proud United States Naval Veteran Submariner who served aboard the USS Whale SSN638 submarine.

Tom is the bestselling author of Advanced, Integrated RPG, which covers the latest programming techniques for RPG ILE and Java to use open-source technologies. His latest book, co-written with Vedish Shah, is Extract, Transform, and Load with SQL Server Integration Services.

Originally from and currently residing in Scranton, Pennsylvania, Tom is currently involved in a mobile application startup company, JoltRabbit LLC.


MC Press books written by Thomas Snyder available now on the MC Press Bookstore.

Advanced, Integrated RPG Advanced, Integrated RPG
See how to take advantage of the latest technologies from within existing RPG applications.
List Price $79.95

Now On Sale

Extract, Transform, and Load with SQL Server Integration Services Extract, Transform, and Load with SQL Server Integration Services
Learn how to implement Microsoft’s SQL Server Integration Services for business applications.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

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: