Simplify Encryption with the Use of RPG Reusable Procedures PDF Print E-mail
Programming - RPG
Written by Thomas Snyder   
Wednesday, 02 December 2009 00:00

Support MC Press - Visit Our Sponsors

 

Forums Sponsor

POPULAR FORUMS

Forums

 

 

Search Sponsor

 

Search

 

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
About the Author:

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

 

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

 

Tom is the best-selling author of Advanced Integrated RPG, which covers the latest programming techniques for RPG ILE and Java to utilize open-source technologies.

 

Originally from and currently residing in Scranton, Pennsylvania. Tom is currently involved in a Mobile Application Start-up company named JoltRabbit LLC.

 

 


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

 

Advanced, Integrated RPG Advanced, Integrated RPG

This book shows you how to take advantage of the latest technologies from within existing RPG applications.

List Price $79.95
Now On Sale
 

 

Read More >>
Last Updated on Monday, 30 November 2009 12:22
 
User Rating: / 11
PoorBest 
   MC-STORE.COM