SlideShare a Scribd company logo
Writing RPG Applications Using Cryptographic Services APIs Presented by Carsten Flensburg RPG & Beyond Web Conference 2008
RPG & Beyond 2008 : Writing RPG Applications using the Cryptographic Services APIs Introduction:  The need to protect sensitive and private data using cryptographic methods is becoming increasingly important to many organizations. The drivers behind this development are legislation, regulations, standards as well as current types of applications requiring such measures and efforts.  Fortunately, the System i operating system includes a versatile, comprehensive and advanced cryptographic API tool set, being significantly enhanced with each release. This session discusses and demonstrates how to design and build RPG applications using the Cryptographic Services APIs.   Objectives of this presentation: Discuss the considerations involved in preparing for an encryption project Learn  how to design and develop applications using the Cryptographic Services APIs Show you where to find information and code examples to get you started in the right direction
Getting the right start:  Where to begin G etting started:  To prepare, organize and execute a data encryption project successfully it is essential to approach and progress the project thoroughly and methodically.  Done right data encryption provides another strong and secure protection layer for your data. Done wrong you not only risk to expose your vital and confidential business data with all the potential damages and huge costs involved, but you also risk to be unable to restore access to your data, which eventually could impose even worse consequences to your business as well as to your reliability with your business partners.  So here’s a brief discussion of the elements and aspects to consider when starting an encryption project: Prepare encryption project Organize encryption project Execute encryption project
Getting the right start:  Where to begin Prepare encryption project Determine the purpose Define the scope Locate sensitive data and determine use Research documentation Establish methods and tools Organize encryption project Create project initialization document (PID) Identify knowledge and decision resources Finalize project planning and manning Verify PID with management Execute encryption project Perform risk assessment Decide encryption algorithms Establish key management setup Review source code and test executables  Monitor application implementation
Getting the right start:  Where to begin Being crucial as it is, and yet out of scope to discuss in greater detail for this session targeted at providing input to encryption programming practice, I’ve included links to a couple of articles covering the topic of data encryption project considerations and guidelines.  Be sure to look up Carol Woodbury’s  Essential Guide to Encryption  as well as the recently published IBM encryption redbook:  IBM System i Security: Protecting i5/OS Data with Encryption . Both publications will provide you with invaluable insight and lots of detailed information to help you getting a head start in the right direction on your data encryption project.
Architecture and design:  What to consider Architecture & design:  How to conceive and organize applications using cryptographic  services APIs to protect sensitive and confidential data due to regulation or legislation requirements or application security design objectives. Cryptography will only offer protection to your data if implemented correctly; the encryption chain is not stronger than the weakest link in the encryption process. Encrypting data essentially provides security comparable to that of other types of access control, including object authority: If someone is given access to the encryption key and encrypted data, access to the clear text data is by definition granted. Perceiving regulations, guidelines and recommendations as important supporting factors early on in the process will help you understanding requirements, scope and implications of the encryption project as well as provide a solid foundation for your efforts.
Architecture and design:  What to consider Application design and implementation considerations : Plan carefully how all the contributing components should interact and fit together to achieve the most secure and strongest possible cryptographic protection of your sensitive data.  Plan key management scheme Establish two- or three tier key hierarchy defining master keys, key encryption keys and data encryption keys  Use key stores and validation lists to store all encryption keys Decide encryption key time-to-live and key translation scheme Control and audit access to cryptographic functions as well as key stores Function usage commands and APIs Security and object audit Protect program source as well as program observability and debug views Externalize encrypted data fields from application files Create separate files to store encrypted data and IVs Clear field values from application files Alternatively use CUSP mode for character fields to preserve encrypted data length (IV must still be stored separately)  Only encrypt sensitive and private data Reduce encryption efforts and costs Minimize encryption key usage Consider using hashing for verification-only usage
Architecture and design:  What to consider Programming guidelines:  Building encryption programs and functions involve a number of potential pitfalls that ultimately could contribute to exposure of sensitive data or encryption keys. Some of the most common and obvious are mentioned below together with recommendations aiming at providing a compact and well organized application. The list however should not be regarded as exhaustive in any way; many exposures and challenges are contextual of nature, depending on the specific circumstances applying, so common sense, careful research and thorough testing is always imperative when cryptographic programming is on the agenda: Discard cryptographic material immediately when no longer needed. Cryptographic keys, tokens and other similar information should be immediately removed or deleted at the point where it will no more be used. Clear program variables containing encryption key information and plain text data to be encrypted as soon as use is completed. Never ever store encryption keys directly in program variables or constants, always use key stores. Storing or transferring cryptographic keys or cipher text in database files or elsewhere in CCSID-sensitive storage locations or channels require a CCSID of 65535 indicating binary values.
Architecture and design:  What to consider Programming guidelines – continued: Encryption configuration parameters such as encryption mode, block length, padding, pad characters and initialization vector (IV) are rightfully often the primary suspects when the decryption or verification process fails. Plain text character set and code page differences provide another source of potential issues in this area. Create simple interfaces targeted at specific requirements to cryptographic services APIs encapsulated in service program subprocedures. Centralize cryptographic subprocedures in specialized cryptographic function service programs and monitor as well as control access to these service programs. Store encryption and configuration parameters in service program functions returning key and algorithm tokens, key stores and labels, library names and other crucial details, rather than hard coding these in individual programs. This approach documents these core parameters and at the same time provides for quicker and less error prone changing efforts, if required.
Code and development:  How to do it Code examples:  Introducing the different cryptographic APIs involved in realizing a cryptographic programming scenario and creating application components and functions providing the necessary, robust and secure cryptographic services to the application being developed. Typically you’ll need to take advantage of a suite of Cryptographic Services APIs as well as other APIs to cover your requirements. For example Validation List APIs if you rely on a three-tier key hierarchy or need to implement a key storage facility at V5R2 or V5R3. For the purpose of demonstrating how the many APIs interact and how a set of encryption service programs and subprocedures could be organized, let us create a starting point for our endeavour in the form of a file field encryption/decryption scenario using the Advanced Encryption Standard (AES) block encryption algorithm and following the recommendations offered in the publications and articles mentioned earlier. To find out exactly what APIs are involved in such a setup let’s take a look at the Encrypt data (Qc3EncryptData) API which is going to perform the actual encryption operation. Here’s the Qc3EncryptData APIs parameter list found at the  Infocenter :
Code and development:  The encrypt API The Qc3EncryptData API parameter list:  1 Clear data   Input Char(*) 2 Length of clear data   Input Binary(4) 3 Clear data format name Input Char(8) 4 Algorithm description   Input Char(*) 5 Algorithm description format name   Input Char(8) 6 Key description Input Char(*) 7 Key description format name   Input Char(8) 8 Cryptographic service provider   Input Char(1) 9 Cryptographic device name   Input Char(10) 10 Encrypted data Output Char(*) 11 Length of area provided for encrypted data Input Binary(4) 12 Length of encrypted data returned   Output Binary(4) 13 Error code   I/O Char(*) Now let’s walk through the parameter list, one by one...
Code and development:  The API parameters The  Clear data  parameter provides the plain text to encrypt. The  Length of clear data  declares the length of the plain text. The  Clear data format name  will be specified as DATA0100 ,  identifying parameter 1 as a text string. The  Algorithm description  is specified in the format ALGD0100, indicating an algorithm context token. Producing the token requires an initialization vector (IV). This parameter simply specifies the format chosen for parameter 4, in this case the value ALGD0100. The  Key description  parameter is specified in the format KEYD0100, indicating a key context token.  Specifies the chosen key description format name, in this case the format name KEYD0100. The  Cryptographic service provider,  defined by the value ‘1’, indicating a software CSP.  The  Cryptographic device name  defines the hardware to use, so blanks is provided for this parameter. The  Encrypted data  output parameter defines the variable to receive the result of the encryption operation.  The  Length of area provided for encrypted data  parameter tells the API the size of the variable provided for the previous parameter.  The  Length of encrypted data returned  output parameter, used by the encryption API to return the length of the produced cipher text. The final parameter is the API standard error data structure complying to format ERRC0100.
Code and development:  The algorithm context token The Create Algorithm Context (Qc3CreateAlgorithmContext) API parameter list: Algorithm description Input Char(*) Algorithm description format name Input Char(8) Algorithm context token Output Char(8) Error code I/O Char(*) The ALGD0200 format that I will be using to describe the AES algorithm configuration parameters: Block cipher algorithm Input Binary(4) Block length Input Binary(4) Mode Input Char(1) Pad option Input Char(1) Pad character Input Char(1) Reserved Input Char(1) MAC length Input Binary(4) Effective key size Input Binary(4) Initialization vector Input Char(32)
Code and development:  The algorithm context parameters The  Create Algorithm Context (Qc3CreateAlgorithmContext) API parameters: The algorithm and the configuration parameters associated to it. The algorithm description format name, in this case ALGD0200. The output algorithm context token. The standard API error data structure ERRC0100.  The ALGD0200 algorithm description data structure: The code identifying the chosen encryption algorithm, for AES that is 22. The algorithm block length. The valid block length values for AES are 16, 24, and 32. The mode of operation. A value of ‘0’ identifies CBC (Cipher Block Chaining) which I will be using. The type of padding to apply, if any. A value of ‘1’ causes character padding to be applied. The value to use for character padding. I use the default value x’00’. A reserved field, x’00’ must be specified. MAC length. Not used in this case so it is set to zero. Effective key size. Not used in this case so it is set to zero. Initialization vector. Used in the initial step of a CBC encryption operation. The leftmost part of equal size to the applied block length is used. This value should be generated by the Generate pseudorandom numbers (Qc3GenPRNs) API.
Code and development:  The key context token The Create Key Context (Qc3CreateKeyContext) API parameter list: Key string Input Char(*) Length of key string Input Binary(4) Key format Input Char(1) Key type Input Binary(4) Key form Input Char(1) Key-encrypting key Input Char(*) Key-encrypting algorithm Input Char(8) Key context token Output Char(8) Error code I/O Char(*) The following slide explains the above parameter list defining the encryption key properties, though only the relevant parameter options are described:
Code and development:  The key context parameters The key string either specifying the binary key value or the key store holding the key value. The length of the key string defined by parameter 1. The format of the key string defined by parameter 1.  The value ‘1’ specifies a binary string, the value ‘4’ a key store. The key type defines the encryption algorithm that the specified key is qualified to be applied to. For AES a value of 22 should be submitted. The key form defines whether a specified binary key value is an unencrypted key string or it is encrypted under a key encryption or master key.  A value of ‘0’ defines a clear key value, ‘1’ a key encrypted key value and ‘2’ a master key encrypted key value. The key encrypting key used if ‘1’ or ‘2’ was specified for parameter 5. For value ‘1’ a key context token defining the key encryption key to be used to decrypt the key value specified must be submitted for this parameter. For value ‘2’ a data structure defining the master key to be used to decrypt the key value specified must be submitted for this parameter. The algorithm context to use for decrypting the specified key value, if a value of ‘1’ was specified for parameter 5. The API output key context token. The standard API error data structure ERRC0100.
Code and development:  The encryption process Giving consideration to the aforementioned requirements, the following encryption process steps involved in transforming a plain text value into a cipher text value have been identified. Note, that I’ll be leaving the key management aspect out of the equation for now, as I’ll cover that separately in a minute. Take input plain text value Generate an initialization vector (IV) Take encryption key and generate a key context token Define encryption algorithm parameters and generate an algorithm context token Encrypt data using the above parameters as input to the operation Clear input plain text value Destroy key context token Destroy algorithm context token Output cipher text value and IV
Code and development:  The process result Upon successful completion of the encryption process I well end up with two values that I must store carefully, in order to be able to recover the plain text value from the cipher text value: Cipher text value including the actual length Initialization vector (IV) The exact length of the cipher text must be available for the decryption process.  The storage location must be insensitive to implicit character set conversions.
Code and development:  Reversing the process At the point where the plain text value is requested, the above encryption process must be reversed, using the exact same parameters for the decryption process, except that now the cipher text value is used as input: Take output cipher text value Take output initialization vector (IV) Take encryption key and generate a key context token Define encryption algorithm parameters and generate an algorithm context token Decrypt data using the above parameters as input to the operation Clear input cipher text value Destroy key context token Destroy algorithm context token Output plain text value
Code and development:  The APIs involved Now let’s look at how to accommodate the above encryption and decryption processes in terms of Cryptographic Services APIs required to perform the necessary steps. As far as the encryption part goes, the following sequence of API calls will do the work: Generate pseudorandom numbers (Qc3GenPRNs) API  (step 2) Create key context (Qc3CreateKeyContext) API  (step 3) Create algorithm context (Qc3CreateAlgorithmContext) API  (step 4) Encrypt data (Qc3EncryptData) API  (step 5) Destroy key context (Qc3DestroyKeyContext) API  (step 7)  Destroy algorithm context (Qc3DestroyAlgorithmContext) API  (step 8)  The decryption process likewise translates into the following sequence of Cryptographic Services API calls: Create key context (Qc3CreateKeyContext) API  (step 3) Create algorithm context (Qc3CreateAlgorithmContext) API    (step 4) Decrypt data (Qc3DecryptData) API  (step 5) Destroy key context (Qc3DestroyKeyContext) API  (step 7)  Destroy algorithm context (Qc3DestroyAlgorithmContext) API  (step 8)
Code and development:  The subprocedures At this point I’m ready to devise the service program subprocedures required to implement the scenario at hand. Consolidating the two API lists I end up with the following array of subprocedures. I’ve specified the Cryptographic Services API that the subprocedure employs in the rightmost column: GenInzVct()  - Generate initialization vector  - Qc3GenPRNs GetKeyCtx()  - Get key context  - Qc3CreateKeyContext GetAlgCtx() - Get algorithm context  - Qc3CreateAlgorithmContext EncDtaStr()  - Encrypt data string  - Qc3EncryptData DecCphStr()  - Decrypt cipher string  - Qc3DecryptData RmvKeyCtx() - Remove key context  - Qc3DestroyKeyContext RmvAlgCtx()  - Remove algorithm context  - Qc3DestroyAlgorithmContext All the above subprocedures can be found in the APIs by Example articles covering the Cryptographic Services APIs that have been published in the System iNetwork Programming Tips Newsletter. Links to these articles are provided at the end of this presentation.
Code and development:  The API prototype If we compare the parameter-structure and –complexity of the subprocedures measured against the APIs, you’ll notice that the subprocedures in most cases are much simpler and more task specific than the equivalent API.  Wrapping up the APIs in subprocedures allow me to expose only the parameters that are relevant for the task at hand and provide default values for the rest.  T he Qc3EncryptData API as specified by the documentation examined earlier requires the following prototype: **-- Encrypt data API:  D EncryptData  Pr  ExtProc( 'Qc3EncryptData' ) D  ClrDta  65535a  Const  Options( *VarSize )  D  ClrDtaLen  10i 0 Const  D  ClrDtaFmt  8a  Const  D  AlgDsc  1024a  Const  Options( *VarSize )  D  AlgDscFmt  8a  Const  D  KeyDsc  1024a  Const  Options( *VarSize )  D  KeyDscFmt  8a  Const  D  CrpSrvPrv  1a  Const  D  CrpDevNam  10a  Const  D  EncDta  65535a  Options( *VarSize )  D  EncDtaLen  10i 0 Const  D  EncRtnLen  10i 0  D  Error  32767a  Options( *VarSize )
Code and development:  The subprocedure Whereas t he EncDtaStr() subprocedure for example has the following interface:   **-- Encrypt data string:    D EncDtaStr  Pr  1024a  Varying    D  PxDtaStr  1024a  Varying  Const    D  PxAlgCtxTkn  8a    D  PxKeyCtxTkn  8a  In most cases I group all encryption related subprocedures in a single encryption function service program. Binding to this service program enables other programs to instantly have all encryption and decryption functions readily available.  Simply copy or use /COPY compiler directives to include the encryption subprocedure prototypes and you’re ready to go as the brief code example on the following slide demonstrates.
Code and development:  A code example /Free InzVctStr = GenInzVct( %Size( InzVctStr ));  AlgCtxTkn = GetAlgCtx( AES  : DFT_BLK_LEN  : CBC  : PAD_CHR  : DFT_PAD_CHR  : InzVctStr  );  KeyCtxTkn = GetKeyCtx( GetDtkRcd( PxKeyStore_q: PxDtkLbl )  : KEY_AES  : FMT_BIN  : KekCtxTkn  : KekAlgTkn  );  CphDtaStr = EncDtaStr( %TrimR( PxCusDta ): AlgCtxTkn: KeyCtxTkn ); PxCusDta = *Blanks;  RmvKeyCtx( KeyCtxTkn );  RmvAlgCtx( AlgCtxTkn ); /End-Free
Code and development:  Key management Design and implementation objectives similar to the ones demonstrated in the previous section discussing the development of cryptographic applications, apply to the important role in the encryption programming discipline belonging to the key management requirement. Group key management functions in service programs Provide simple and specialized interface to key management APIs Only core functionality remains in application programs Control and audit access to key management functions and key stores Employ function usage commands and APIs Configure security and object audit Prior to release V5R4 no native key management support was available on the System i. The recommended approach for release V5R3 and earlier is to use validation lists to store encryption keys.  Validation lists store list entry data encrypted and are only accessible through APIs. You can monitor and control access to validation lists using the security audit facility and object authority, respectively.
Code and development:  Key management At release V5R4 and later, a native two-tier key store facility is available. At V5R4 APIs are the only option for key store administration and maintenance. A number of APIs by Example articles provided CL commands for this purpose, based on the APIs. More detailed information about the V5R4 key management enhancements can be found in Beth Hagemeister’s System iNews article:  Cryptographic Services APIs: Key Management For V6R1 and later, native key management CL commands have been provided. V6R1 also brought additions to the key management API set as well as a master key back up facility. More information about these enhancements can be found in the recent APIs by Example Cryptographic Key Management articles. Establishing a three-tier key store facility still require validation list support. V5R3 and earlier:  Validation list key stores and APIs by Example validation list key  management CL commands V5R4 and later:  Native two-tier key store facility and APIs by Example key  management CL commands V6R1 and later:  Native key management CL commands and API enhancements
Code and development:  Key management basics The key management facility, whether provided by validation lists or native key stores, is based on an encryption key hierarchy. A two-tier key hierarchy is made up by a master key level at the top and a data key level at the bottom. A three-tier key hierarchy has a key encryption key level between the master key level and the data key level: Master key Key encryption key  Data encryption key In a three-tier key hierarchy a master key encrypts the key encryption key and the key encryption key encrypts the data encryption key. This way all keys but the master key is stored encrypted and thereby protected against exposure.  At V5R4 the master key is stored in a protected system area below the LIC (Licensed Internal Code) layer, only accessible to system functions and APIs. Further the master key is constructed by a number of passphrases, each ideally only known to different individuals. So no single person will know all the master key components, and consequently no single person be able to generate the master key on their own.  Up to 8 different master keys can be created and maintained on a single system.
Code and development:  Key management basics When a key store is created, one of the system master keys is assigned to the key store and all encryption keys, key encryption keys or data encryption keys, stored in the key store will be encrypted under the assigned master key. Each key stored in a key store is identified by a key label named when the key is added to the key store.  All cryptographic operations performed by encryption keys stored in a key store references the encryption key by the label naming it, and the system takes care of decrypting the key before it is used in the cryptographic operation. Instead of specifying a key value to the cryptographic API of choice you provide a data structure defining the qualified name of the key store as well as the key label. Using key context tokens to mediate the encryption key value all this happens in the system domain and the key value itself is never exposed, since only the key context token is returned. As mentioned, key stores support a two-tier key hierarchy, providing a safe storage location for both key encryption and data encryption keys. To have separate key stores for key encryption keys and data encryption keys, still involves the pre-V5R4 validation list key store.
Code and development:  Validation list APIs The validation list APIs required to build a key store facility include the following APIs: Add validation list entry (QsyAddValidationLstEntry) API Remove validation list entry (QsyRemoveValidationLstEntry) API Find validation list entry (QsyFindValidationLstEntry) API Find validation list entry attributes (QsyFindValidationLstEntryAttrs) API Find first validation list entry (QsyFindFirstValidationLstEntry) API Find next validation list entry (QsyFindNextValidationLstEntry) API Change validation list entry (QsyChangeValidationLstEntry) API  Transforming the above list into key store management subprocedures leads to the following list of key management function. I’ve specified the Validation List API(s) that the subprocedure exploits in the rightmost column: AddDtkEnt()  - Add data key entry    - QsyAddValidationLstEntry ChgDtkEnt()  - Change data key entry - QsyChangeValidationLstEntry RmvDtkEnt()  - Remove data key entry  - QsyRemoveValidationLstEntry VfyDtkEnt()  - Verify data key entry   - QsyFindValidationLstEntry GetDtkAtr()  - Get data key attribute  - QsyFindValidationLstEntry GetDtkRcd()  - Get data key record   - QsyFindValidationLstEntry FndTopDtkE() - Find top data key entry - QsyFindFirstValidationLstEntry FndNxtDtkE() - Find next data key entry - QsyFindNextValidationLstEntry
Code and development:  Validation list APIs All key management subprocedures employs the function usage APIs to ensure that only explicitly function usage authorized user profiles are allowed to perform the subprocedure key management function.  All the subprocedures on the previous slide can be found in the APIs by Example articles covering the Cryptographic Services APIs that have been published in the System iNetwork Programming Tips Newsletter. Again, links to these articles are provided at the end of this presentation.
Code and development:  Key management APIs I’ve written a number of articles, code examples as well as CL commands demonstrating the use and taking advantage of the V5R4 key management APIs and key stores.  The Cryptographic Services Key Management APIs at V5R4 covered so far in the APIs by Example second cryptographic article series: Load master key part (Qc3LoadMasterKeyPart) API Set master key (Qc3SetMasterKey) API Test master key (Qc3TestMasterKey) API Clear master key (Qc3ClearMasterKey) API Create key store (Qc3CreateKeyStore) API Translate key store (Qc3TranslateKeyStore) API Generate key record (Qc3GenKeyRecord) API  Delete key record (Qc3DeleteKeyRecord) API  Retrieve key record attributes (Qc3RetrieveKeyRecordAtr) API V5R4 Cryptographic Services Key Management APIs not covered yet: The Export Key (Qc3ExportKey) API The Extract Public Key (Qc3ExtractPublicKey) API The Import Key (Qc3ImportKey) API The Write Key Record (Qc3WriteKeyRecord) API V6R1 Cryptographic Service Key Management APIs not covered yet: The Retrieve Key Store File Attributes (Qc3RetrieveKeyStoreFileAtr) API The Retrieve Key Store Records (Qc3RetrieveKeyStoreRecords) API The Translate Key (Qc3TranslateKey) API
Code and development:  Key management CL commands APIs by Example Key Management CL commands at V5R4: Load Master Key Part (LODMSTKP) Set Master Key (SETMSTK)  Test Master Key (TSTMSTK) Clear Master Key (CLRMSTK)  Create Key Store (CRTKS)  Translate Key Store (TRNKS)  Generate Key Record (GENKR)  Display Key Record Attributes (DSPKRA)  Delete Key Record (DLTKR) Cryptographic Services Key Management CL commands at V6R1: Add Master Key Part (ADDMSTPART) Set Master Key (SETMSTKEY)  Check Master KVV (CHKMSTKVV) Clear Master Key (CLRMSTKEY) Add Keystore File Entry (ADDCKMKSFE) Create Keystore File (CRTCKMKSF) Display Keystore File Entry (DSPCKMKSFE) Generate Keystore File Entry (GENCKMKSFE) Remove Keystore File Entry (RMVCKMKSFE) Translate Keystore File (TRNCKMKSF)
More Information on the Web Cryptography documentation : Carol Woodbury: The Essential Guide to Encryption, April 2006 http://systeminetwork.com/node/60013 Beth Hagemeister: Cryptographic Services APIs: Key Management: http://systeminetwork.com/article/cryptographic-services-apis-key-management Bruce Schneier: Computer Security Articles http://www.schneier.com/essays-comp.html AES Algorithm: http://en.wikipedia.org/wiki/AES The Rijndael page: http://www.iaik.tugraz.at/Research/krypto/AES/old/~rijmen/rijndael/ Encrypting Credit Card Numbers in a Database: http://www.di-mgt.com.au/cryptoCreditcard.html An Introduction to Using Keys in Encryption: http://www.di-mgt.com.au/cryptokeys.html Encryption with International Character Sets: http://www.di-mgt.com.au/cryptoInternational.html Using Padding in Encryption: http://www.di-mgt.com.au/cryptopad.html
More Information on IBM Websites IBM documentation: Educational White Paper: Protecting i5/OS Data with Encryption: http://www-03.ibm.com/servers/enable/site/education/abstracts/efbe_abs.html IBM System i Security: Protecting i5/OS Data with Encryption: http://www.redbooks.ibm.com/Redbooks.nsf/RedpieceAbstracts/sg247399.html?Open Cryptographic Services APIs V5R4: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/topic/apis/catcrypt.htm i5/OS: Cryptography concepts V5R4: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/topic/rzajc/rzajcconcepts.htm Scenario: Key Management and File Encryption Using the Cryptographic Services APIs V5R4: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/topic/apis/qc3Scenario.htm Cryptographic Services APIs 6.1: http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/apis/catcrypt.htm i5/OS: Cryptography concepts 6.1: http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/rzajc/rzajcconcepts.htm Cryptographic Services Key Management 6.1: http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/rzajc/rzajckeymgmt.htm Disk Encryption 6.1: http:// publib.boulder.ibm.com /infocenter/systems/ scope /i5os/ topic / rzaly / rzalyencrypt.htm Backing Up Encrypted Auxiliary Storage Pools 6.1: http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/rzaiu/rzaiuencryptasp.htm Saving and Restoring Master Keys 6.1: http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/rzajc/rzajcsavemasterkey.htm
More Information on System iNetwork Previously published articles: Compliance Encryption: A System i Signature http://systeminetwork.com/article/compliance-encryption-system-i-signature If You're Using Random Numbers, You Really Need This New Command http://systeminetwork.com/article/if-youre-using-random-numbers-you-really-need-new-command APIs by Example: Cryptographic Services APIs, Part 1 :   http://systeminetwork.com/article/apis-example-cryptographic-services-apis APIs by Example: Cryptographic Services APIs, Part 2 :   http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-2 APIs by Example: Cryptographic Services APIs, Part 3 :   http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-3 APIs by Example: Cryptographic Services APIs, Part 4 :   http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-4 APIs by Example: Cryptographic Services APIs, Part 5 :   http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-5 APIs by Example: Cryptographic Services APIs, Part 6 :   http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-6 APIs by Example: Cryptographic Services APIs, Part 7 :   http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-7
More Information on System iNetwork Previously published articles - continued: APIs by Example: Crypto Key Management - Loading and Setting Master Keys: http://systeminetwork.com/article/apis-example-cryptographic-key-management-loading-and-setting-master-keys APIs by Example: Crypto Key Management - Testing and Clearing Master Keys: http://systeminetwork.com/article/apis-example-cryptographic-key-management-testing-and-clearing-master-keys APIs by Example: Crypto Key Management – Creating and Translating Key Stores: http://systeminetwork.com/article/apis-example-cryptographic-key-management-creating-and-translating-key-stores APIs by Example:  Crypto Key Management – Creating, Displaying, and Deleting Key Records: http://systeminetwork.com/article/apis-example-cryptographic-key-management-%E2%80%93-creating-displaying-and-deleting-key-records APIs by Example: Crypto Key Management - Creating Data Key Stores and More: http://systeminetwork.com/article/apis-example-crypto-key-management-creating-data-key-stores-and-more APIs by Example: Crypto Key Management - Encrypt/Decrypt with Key Hierarchy: http://systeminetwork.com/article/apis-example-crypto-key-mgmt-encryptdecrypt-key-hierarchy APIs by Example: AES Encryption to Actual Field Length: http://systeminetwork.com/article/apis-example-aes-encryption-actual-field-length
RPG & Beyond 2008 : Writing RPG Applications using the Cryptographic Services APIs – The End Presentation completed! Questions concerning presentation, encryption topics or code snippets can be directed to me at: [email_address] Thank you!

More Related Content

PDF
[212]C3, 데이터 처리에서 서빙까지 가능한 하둡 클러스터
PDF
Cloud dw benchmark using tpd-ds( Snowflake vs Redshift vs EMR Hive )
PPTX
Yarn resource-manager
PPT
REVIEW PAPER on Scheduling in Cloud Computing
PDF
Aws guard duty security monitoring service
PDF
Comparison of-foss-distributed-storage
PPTX
Security in microservices architectures
PPTX
Security in Cloud Computing
[212]C3, 데이터 처리에서 서빙까지 가능한 하둡 클러스터
Cloud dw benchmark using tpd-ds( Snowflake vs Redshift vs EMR Hive )
Yarn resource-manager
REVIEW PAPER on Scheduling in Cloud Computing
Aws guard duty security monitoring service
Comparison of-foss-distributed-storage
Security in microservices architectures
Security in Cloud Computing

What's hot (20)

PPT
Storage, San And Business Continuity Overview
PDF
[AWS & 베스핀글로벌, 바이오∙헬스케어∙제약사를 위한 세미나] AWS 클라우드 보안
PDF
Amazon Redshift 아키텍처 및 모범사례::김민성::AWS Summit Seoul 2018
PDF
Different types of virtualisation
PPTX
Graph database
PPTX
Lecture01: Introduction to Security and Privacy in Cloud Computing
PPT
Cloud computing
PDF
Amazon Redshift의 이해와 활용 (김용우) - AWS DB Day
PDF
Zerto virtual replication 5.0 표준소개자료
PDF
Lecture5 virtualization
PPTX
Spark introduction and architecture
PDF
Jurnal msdm
PPTX
Cloud Computing in a Nutshell
PPTX
Virtual Machine
PPT
data hiding techniques.ppt
PDF
Integration between Filebeat and logstash
PPT
Chapter 6
PDF
천만 사용자를 위한 AWS 아키텍처 보안 모범 사례 (윤석찬, 테크에반젤리스트)
PDF
An Overview of Spanner: Google's Globally Distributed Database
PDF
네이버클라우드플랫폼이 제안하는 멀티클라우드(박기은 CTO) - IBM 스토리지 세미나
Storage, San And Business Continuity Overview
[AWS & 베스핀글로벌, 바이오∙헬스케어∙제약사를 위한 세미나] AWS 클라우드 보안
Amazon Redshift 아키텍처 및 모범사례::김민성::AWS Summit Seoul 2018
Different types of virtualisation
Graph database
Lecture01: Introduction to Security and Privacy in Cloud Computing
Cloud computing
Amazon Redshift의 이해와 활용 (김용우) - AWS DB Day
Zerto virtual replication 5.0 표준소개자료
Lecture5 virtualization
Spark introduction and architecture
Jurnal msdm
Cloud Computing in a Nutshell
Virtual Machine
data hiding techniques.ppt
Integration between Filebeat and logstash
Chapter 6
천만 사용자를 위한 AWS 아키텍처 보안 모범 사례 (윤석찬, 테크에반젤리스트)
An Overview of Spanner: Google's Globally Distributed Database
네이버클라우드플랫폼이 제안하는 멀티클라우드(박기은 CTO) - IBM 스토리지 세미나
Ad

Similar to Writing RPG Applications Using Cryptographic Services APIs (20)

PDF
Perth Meetup August 2021
DOC
chaitraresume
PDF
"Exploring MACH Principles", Nikita Galkin
PDF
Qa Financials - 10 Smart Controls for Software Development
PDF
IRJET- Privacy Preserving Encrypted Keyword Search Schemes
DOCX
Enhanced Hybrid Blowfish and ECC Encryption to Secure cloud Data Access and S...
PPTX
Symmetric key encryption
PDF
Mobile App Security - Best Practices
PDF
Application Programming Interface
PDF
AWS User Group November
PDF
AWS November meetup Slides
PDF
Full-Stack .NET Developer Interview Questions PDF By ScholarHat
PPTX
Encryption symmetric key
PDF
Detecting Malicious Cloud Account Behavior: A Look at the New Native Platform...
PPTX
Integrate Security into DevOps - SecDevOps
DOC
Internet security evaluation system documentation nikitha
PPTX
PCI: Building Compliant Applications in the Public Cloud - RightScale Compute...
PDF
Bridging the Security Testing Gap in Your CI/CD Pipeline
PPT
Adobe PDF and LiveCycle ES Security
PPTX
Secure Design: Threat Modeling
Perth Meetup August 2021
chaitraresume
"Exploring MACH Principles", Nikita Galkin
Qa Financials - 10 Smart Controls for Software Development
IRJET- Privacy Preserving Encrypted Keyword Search Schemes
Enhanced Hybrid Blowfish and ECC Encryption to Secure cloud Data Access and S...
Symmetric key encryption
Mobile App Security - Best Practices
Application Programming Interface
AWS User Group November
AWS November meetup Slides
Full-Stack .NET Developer Interview Questions PDF By ScholarHat
Encryption symmetric key
Detecting Malicious Cloud Account Behavior: A Look at the New Native Platform...
Integrate Security into DevOps - SecDevOps
Internet security evaluation system documentation nikitha
PCI: Building Compliant Applications in the Public Cloud - RightScale Compute...
Bridging the Security Testing Gap in Your CI/CD Pipeline
Adobe PDF and LiveCycle ES Security
Secure Design: Threat Modeling
Ad

Writing RPG Applications Using Cryptographic Services APIs

  • 1. Writing RPG Applications Using Cryptographic Services APIs Presented by Carsten Flensburg RPG & Beyond Web Conference 2008
  • 2. RPG & Beyond 2008 : Writing RPG Applications using the Cryptographic Services APIs Introduction: The need to protect sensitive and private data using cryptographic methods is becoming increasingly important to many organizations. The drivers behind this development are legislation, regulations, standards as well as current types of applications requiring such measures and efforts. Fortunately, the System i operating system includes a versatile, comprehensive and advanced cryptographic API tool set, being significantly enhanced with each release. This session discusses and demonstrates how to design and build RPG applications using the Cryptographic Services APIs. Objectives of this presentation: Discuss the considerations involved in preparing for an encryption project Learn how to design and develop applications using the Cryptographic Services APIs Show you where to find information and code examples to get you started in the right direction
  • 3. Getting the right start: Where to begin G etting started: To prepare, organize and execute a data encryption project successfully it is essential to approach and progress the project thoroughly and methodically. Done right data encryption provides another strong and secure protection layer for your data. Done wrong you not only risk to expose your vital and confidential business data with all the potential damages and huge costs involved, but you also risk to be unable to restore access to your data, which eventually could impose even worse consequences to your business as well as to your reliability with your business partners. So here’s a brief discussion of the elements and aspects to consider when starting an encryption project: Prepare encryption project Organize encryption project Execute encryption project
  • 4. Getting the right start: Where to begin Prepare encryption project Determine the purpose Define the scope Locate sensitive data and determine use Research documentation Establish methods and tools Organize encryption project Create project initialization document (PID) Identify knowledge and decision resources Finalize project planning and manning Verify PID with management Execute encryption project Perform risk assessment Decide encryption algorithms Establish key management setup Review source code and test executables Monitor application implementation
  • 5. Getting the right start: Where to begin Being crucial as it is, and yet out of scope to discuss in greater detail for this session targeted at providing input to encryption programming practice, I’ve included links to a couple of articles covering the topic of data encryption project considerations and guidelines. Be sure to look up Carol Woodbury’s Essential Guide to Encryption as well as the recently published IBM encryption redbook: IBM System i Security: Protecting i5/OS Data with Encryption . Both publications will provide you with invaluable insight and lots of detailed information to help you getting a head start in the right direction on your data encryption project.
  • 6. Architecture and design: What to consider Architecture & design: How to conceive and organize applications using cryptographic services APIs to protect sensitive and confidential data due to regulation or legislation requirements or application security design objectives. Cryptography will only offer protection to your data if implemented correctly; the encryption chain is not stronger than the weakest link in the encryption process. Encrypting data essentially provides security comparable to that of other types of access control, including object authority: If someone is given access to the encryption key and encrypted data, access to the clear text data is by definition granted. Perceiving regulations, guidelines and recommendations as important supporting factors early on in the process will help you understanding requirements, scope and implications of the encryption project as well as provide a solid foundation for your efforts.
  • 7. Architecture and design: What to consider Application design and implementation considerations : Plan carefully how all the contributing components should interact and fit together to achieve the most secure and strongest possible cryptographic protection of your sensitive data. Plan key management scheme Establish two- or three tier key hierarchy defining master keys, key encryption keys and data encryption keys Use key stores and validation lists to store all encryption keys Decide encryption key time-to-live and key translation scheme Control and audit access to cryptographic functions as well as key stores Function usage commands and APIs Security and object audit Protect program source as well as program observability and debug views Externalize encrypted data fields from application files Create separate files to store encrypted data and IVs Clear field values from application files Alternatively use CUSP mode for character fields to preserve encrypted data length (IV must still be stored separately) Only encrypt sensitive and private data Reduce encryption efforts and costs Minimize encryption key usage Consider using hashing for verification-only usage
  • 8. Architecture and design: What to consider Programming guidelines: Building encryption programs and functions involve a number of potential pitfalls that ultimately could contribute to exposure of sensitive data or encryption keys. Some of the most common and obvious are mentioned below together with recommendations aiming at providing a compact and well organized application. The list however should not be regarded as exhaustive in any way; many exposures and challenges are contextual of nature, depending on the specific circumstances applying, so common sense, careful research and thorough testing is always imperative when cryptographic programming is on the agenda: Discard cryptographic material immediately when no longer needed. Cryptographic keys, tokens and other similar information should be immediately removed or deleted at the point where it will no more be used. Clear program variables containing encryption key information and plain text data to be encrypted as soon as use is completed. Never ever store encryption keys directly in program variables or constants, always use key stores. Storing or transferring cryptographic keys or cipher text in database files or elsewhere in CCSID-sensitive storage locations or channels require a CCSID of 65535 indicating binary values.
  • 9. Architecture and design: What to consider Programming guidelines – continued: Encryption configuration parameters such as encryption mode, block length, padding, pad characters and initialization vector (IV) are rightfully often the primary suspects when the decryption or verification process fails. Plain text character set and code page differences provide another source of potential issues in this area. Create simple interfaces targeted at specific requirements to cryptographic services APIs encapsulated in service program subprocedures. Centralize cryptographic subprocedures in specialized cryptographic function service programs and monitor as well as control access to these service programs. Store encryption and configuration parameters in service program functions returning key and algorithm tokens, key stores and labels, library names and other crucial details, rather than hard coding these in individual programs. This approach documents these core parameters and at the same time provides for quicker and less error prone changing efforts, if required.
  • 10. Code and development: How to do it Code examples: Introducing the different cryptographic APIs involved in realizing a cryptographic programming scenario and creating application components and functions providing the necessary, robust and secure cryptographic services to the application being developed. Typically you’ll need to take advantage of a suite of Cryptographic Services APIs as well as other APIs to cover your requirements. For example Validation List APIs if you rely on a three-tier key hierarchy or need to implement a key storage facility at V5R2 or V5R3. For the purpose of demonstrating how the many APIs interact and how a set of encryption service programs and subprocedures could be organized, let us create a starting point for our endeavour in the form of a file field encryption/decryption scenario using the Advanced Encryption Standard (AES) block encryption algorithm and following the recommendations offered in the publications and articles mentioned earlier. To find out exactly what APIs are involved in such a setup let’s take a look at the Encrypt data (Qc3EncryptData) API which is going to perform the actual encryption operation. Here’s the Qc3EncryptData APIs parameter list found at the Infocenter :
  • 11. Code and development: The encrypt API The Qc3EncryptData API parameter list: 1 Clear data Input Char(*) 2 Length of clear data Input Binary(4) 3 Clear data format name Input Char(8) 4 Algorithm description Input Char(*) 5 Algorithm description format name Input Char(8) 6 Key description Input Char(*) 7 Key description format name Input Char(8) 8 Cryptographic service provider Input Char(1) 9 Cryptographic device name Input Char(10) 10 Encrypted data Output Char(*) 11 Length of area provided for encrypted data Input Binary(4) 12 Length of encrypted data returned Output Binary(4) 13 Error code I/O Char(*) Now let’s walk through the parameter list, one by one...
  • 12. Code and development: The API parameters The Clear data parameter provides the plain text to encrypt. The Length of clear data declares the length of the plain text. The Clear data format name will be specified as DATA0100 , identifying parameter 1 as a text string. The Algorithm description is specified in the format ALGD0100, indicating an algorithm context token. Producing the token requires an initialization vector (IV). This parameter simply specifies the format chosen for parameter 4, in this case the value ALGD0100. The Key description parameter is specified in the format KEYD0100, indicating a key context token. Specifies the chosen key description format name, in this case the format name KEYD0100. The Cryptographic service provider, defined by the value ‘1’, indicating a software CSP. The Cryptographic device name defines the hardware to use, so blanks is provided for this parameter. The Encrypted data output parameter defines the variable to receive the result of the encryption operation. The Length of area provided for encrypted data parameter tells the API the size of the variable provided for the previous parameter. The Length of encrypted data returned output parameter, used by the encryption API to return the length of the produced cipher text. The final parameter is the API standard error data structure complying to format ERRC0100.
  • 13. Code and development: The algorithm context token The Create Algorithm Context (Qc3CreateAlgorithmContext) API parameter list: Algorithm description Input Char(*) Algorithm description format name Input Char(8) Algorithm context token Output Char(8) Error code I/O Char(*) The ALGD0200 format that I will be using to describe the AES algorithm configuration parameters: Block cipher algorithm Input Binary(4) Block length Input Binary(4) Mode Input Char(1) Pad option Input Char(1) Pad character Input Char(1) Reserved Input Char(1) MAC length Input Binary(4) Effective key size Input Binary(4) Initialization vector Input Char(32)
  • 14. Code and development: The algorithm context parameters The Create Algorithm Context (Qc3CreateAlgorithmContext) API parameters: The algorithm and the configuration parameters associated to it. The algorithm description format name, in this case ALGD0200. The output algorithm context token. The standard API error data structure ERRC0100. The ALGD0200 algorithm description data structure: The code identifying the chosen encryption algorithm, for AES that is 22. The algorithm block length. The valid block length values for AES are 16, 24, and 32. The mode of operation. A value of ‘0’ identifies CBC (Cipher Block Chaining) which I will be using. The type of padding to apply, if any. A value of ‘1’ causes character padding to be applied. The value to use for character padding. I use the default value x’00’. A reserved field, x’00’ must be specified. MAC length. Not used in this case so it is set to zero. Effective key size. Not used in this case so it is set to zero. Initialization vector. Used in the initial step of a CBC encryption operation. The leftmost part of equal size to the applied block length is used. This value should be generated by the Generate pseudorandom numbers (Qc3GenPRNs) API.
  • 15. Code and development: The key context token The Create Key Context (Qc3CreateKeyContext) API parameter list: Key string Input Char(*) Length of key string Input Binary(4) Key format Input Char(1) Key type Input Binary(4) Key form Input Char(1) Key-encrypting key Input Char(*) Key-encrypting algorithm Input Char(8) Key context token Output Char(8) Error code I/O Char(*) The following slide explains the above parameter list defining the encryption key properties, though only the relevant parameter options are described:
  • 16. Code and development: The key context parameters The key string either specifying the binary key value or the key store holding the key value. The length of the key string defined by parameter 1. The format of the key string defined by parameter 1. The value ‘1’ specifies a binary string, the value ‘4’ a key store. The key type defines the encryption algorithm that the specified key is qualified to be applied to. For AES a value of 22 should be submitted. The key form defines whether a specified binary key value is an unencrypted key string or it is encrypted under a key encryption or master key. A value of ‘0’ defines a clear key value, ‘1’ a key encrypted key value and ‘2’ a master key encrypted key value. The key encrypting key used if ‘1’ or ‘2’ was specified for parameter 5. For value ‘1’ a key context token defining the key encryption key to be used to decrypt the key value specified must be submitted for this parameter. For value ‘2’ a data structure defining the master key to be used to decrypt the key value specified must be submitted for this parameter. The algorithm context to use for decrypting the specified key value, if a value of ‘1’ was specified for parameter 5. The API output key context token. The standard API error data structure ERRC0100.
  • 17. Code and development: The encryption process Giving consideration to the aforementioned requirements, the following encryption process steps involved in transforming a plain text value into a cipher text value have been identified. Note, that I’ll be leaving the key management aspect out of the equation for now, as I’ll cover that separately in a minute. Take input plain text value Generate an initialization vector (IV) Take encryption key and generate a key context token Define encryption algorithm parameters and generate an algorithm context token Encrypt data using the above parameters as input to the operation Clear input plain text value Destroy key context token Destroy algorithm context token Output cipher text value and IV
  • 18. Code and development: The process result Upon successful completion of the encryption process I well end up with two values that I must store carefully, in order to be able to recover the plain text value from the cipher text value: Cipher text value including the actual length Initialization vector (IV) The exact length of the cipher text must be available for the decryption process. The storage location must be insensitive to implicit character set conversions.
  • 19. Code and development: Reversing the process At the point where the plain text value is requested, the above encryption process must be reversed, using the exact same parameters for the decryption process, except that now the cipher text value is used as input: Take output cipher text value Take output initialization vector (IV) Take encryption key and generate a key context token Define encryption algorithm parameters and generate an algorithm context token Decrypt data using the above parameters as input to the operation Clear input cipher text value Destroy key context token Destroy algorithm context token Output plain text value
  • 20. Code and development: The APIs involved Now let’s look at how to accommodate the above encryption and decryption processes in terms of Cryptographic Services APIs required to perform the necessary steps. As far as the encryption part goes, the following sequence of API calls will do the work: Generate pseudorandom numbers (Qc3GenPRNs) API (step 2) Create key context (Qc3CreateKeyContext) API (step 3) Create algorithm context (Qc3CreateAlgorithmContext) API (step 4) Encrypt data (Qc3EncryptData) API (step 5) Destroy key context (Qc3DestroyKeyContext) API (step 7) Destroy algorithm context (Qc3DestroyAlgorithmContext) API (step 8) The decryption process likewise translates into the following sequence of Cryptographic Services API calls: Create key context (Qc3CreateKeyContext) API (step 3) Create algorithm context (Qc3CreateAlgorithmContext) API (step 4) Decrypt data (Qc3DecryptData) API (step 5) Destroy key context (Qc3DestroyKeyContext) API (step 7) Destroy algorithm context (Qc3DestroyAlgorithmContext) API (step 8)
  • 21. Code and development: The subprocedures At this point I’m ready to devise the service program subprocedures required to implement the scenario at hand. Consolidating the two API lists I end up with the following array of subprocedures. I’ve specified the Cryptographic Services API that the subprocedure employs in the rightmost column: GenInzVct() - Generate initialization vector - Qc3GenPRNs GetKeyCtx() - Get key context - Qc3CreateKeyContext GetAlgCtx() - Get algorithm context - Qc3CreateAlgorithmContext EncDtaStr() - Encrypt data string - Qc3EncryptData DecCphStr() - Decrypt cipher string - Qc3DecryptData RmvKeyCtx() - Remove key context - Qc3DestroyKeyContext RmvAlgCtx() - Remove algorithm context - Qc3DestroyAlgorithmContext All the above subprocedures can be found in the APIs by Example articles covering the Cryptographic Services APIs that have been published in the System iNetwork Programming Tips Newsletter. Links to these articles are provided at the end of this presentation.
  • 22. Code and development: The API prototype If we compare the parameter-structure and –complexity of the subprocedures measured against the APIs, you’ll notice that the subprocedures in most cases are much simpler and more task specific than the equivalent API. Wrapping up the APIs in subprocedures allow me to expose only the parameters that are relevant for the task at hand and provide default values for the rest. T he Qc3EncryptData API as specified by the documentation examined earlier requires the following prototype: **-- Encrypt data API: D EncryptData Pr ExtProc( 'Qc3EncryptData' ) D ClrDta 65535a Const Options( *VarSize ) D ClrDtaLen 10i 0 Const D ClrDtaFmt 8a Const D AlgDsc 1024a Const Options( *VarSize ) D AlgDscFmt 8a Const D KeyDsc 1024a Const Options( *VarSize ) D KeyDscFmt 8a Const D CrpSrvPrv 1a Const D CrpDevNam 10a Const D EncDta 65535a Options( *VarSize ) D EncDtaLen 10i 0 Const D EncRtnLen 10i 0 D Error 32767a Options( *VarSize )
  • 23. Code and development: The subprocedure Whereas t he EncDtaStr() subprocedure for example has the following interface: **-- Encrypt data string: D EncDtaStr Pr 1024a Varying D PxDtaStr 1024a Varying Const D PxAlgCtxTkn 8a D PxKeyCtxTkn 8a In most cases I group all encryption related subprocedures in a single encryption function service program. Binding to this service program enables other programs to instantly have all encryption and decryption functions readily available. Simply copy or use /COPY compiler directives to include the encryption subprocedure prototypes and you’re ready to go as the brief code example on the following slide demonstrates.
  • 24. Code and development: A code example /Free InzVctStr = GenInzVct( %Size( InzVctStr )); AlgCtxTkn = GetAlgCtx( AES : DFT_BLK_LEN : CBC : PAD_CHR : DFT_PAD_CHR : InzVctStr ); KeyCtxTkn = GetKeyCtx( GetDtkRcd( PxKeyStore_q: PxDtkLbl ) : KEY_AES : FMT_BIN : KekCtxTkn : KekAlgTkn ); CphDtaStr = EncDtaStr( %TrimR( PxCusDta ): AlgCtxTkn: KeyCtxTkn ); PxCusDta = *Blanks; RmvKeyCtx( KeyCtxTkn ); RmvAlgCtx( AlgCtxTkn ); /End-Free
  • 25. Code and development: Key management Design and implementation objectives similar to the ones demonstrated in the previous section discussing the development of cryptographic applications, apply to the important role in the encryption programming discipline belonging to the key management requirement. Group key management functions in service programs Provide simple and specialized interface to key management APIs Only core functionality remains in application programs Control and audit access to key management functions and key stores Employ function usage commands and APIs Configure security and object audit Prior to release V5R4 no native key management support was available on the System i. The recommended approach for release V5R3 and earlier is to use validation lists to store encryption keys. Validation lists store list entry data encrypted and are only accessible through APIs. You can monitor and control access to validation lists using the security audit facility and object authority, respectively.
  • 26. Code and development: Key management At release V5R4 and later, a native two-tier key store facility is available. At V5R4 APIs are the only option for key store administration and maintenance. A number of APIs by Example articles provided CL commands for this purpose, based on the APIs. More detailed information about the V5R4 key management enhancements can be found in Beth Hagemeister’s System iNews article: Cryptographic Services APIs: Key Management For V6R1 and later, native key management CL commands have been provided. V6R1 also brought additions to the key management API set as well as a master key back up facility. More information about these enhancements can be found in the recent APIs by Example Cryptographic Key Management articles. Establishing a three-tier key store facility still require validation list support. V5R3 and earlier: Validation list key stores and APIs by Example validation list key management CL commands V5R4 and later: Native two-tier key store facility and APIs by Example key management CL commands V6R1 and later: Native key management CL commands and API enhancements
  • 27. Code and development: Key management basics The key management facility, whether provided by validation lists or native key stores, is based on an encryption key hierarchy. A two-tier key hierarchy is made up by a master key level at the top and a data key level at the bottom. A three-tier key hierarchy has a key encryption key level between the master key level and the data key level: Master key Key encryption key Data encryption key In a three-tier key hierarchy a master key encrypts the key encryption key and the key encryption key encrypts the data encryption key. This way all keys but the master key is stored encrypted and thereby protected against exposure. At V5R4 the master key is stored in a protected system area below the LIC (Licensed Internal Code) layer, only accessible to system functions and APIs. Further the master key is constructed by a number of passphrases, each ideally only known to different individuals. So no single person will know all the master key components, and consequently no single person be able to generate the master key on their own. Up to 8 different master keys can be created and maintained on a single system.
  • 28. Code and development: Key management basics When a key store is created, one of the system master keys is assigned to the key store and all encryption keys, key encryption keys or data encryption keys, stored in the key store will be encrypted under the assigned master key. Each key stored in a key store is identified by a key label named when the key is added to the key store. All cryptographic operations performed by encryption keys stored in a key store references the encryption key by the label naming it, and the system takes care of decrypting the key before it is used in the cryptographic operation. Instead of specifying a key value to the cryptographic API of choice you provide a data structure defining the qualified name of the key store as well as the key label. Using key context tokens to mediate the encryption key value all this happens in the system domain and the key value itself is never exposed, since only the key context token is returned. As mentioned, key stores support a two-tier key hierarchy, providing a safe storage location for both key encryption and data encryption keys. To have separate key stores for key encryption keys and data encryption keys, still involves the pre-V5R4 validation list key store.
  • 29. Code and development: Validation list APIs The validation list APIs required to build a key store facility include the following APIs: Add validation list entry (QsyAddValidationLstEntry) API Remove validation list entry (QsyRemoveValidationLstEntry) API Find validation list entry (QsyFindValidationLstEntry) API Find validation list entry attributes (QsyFindValidationLstEntryAttrs) API Find first validation list entry (QsyFindFirstValidationLstEntry) API Find next validation list entry (QsyFindNextValidationLstEntry) API Change validation list entry (QsyChangeValidationLstEntry) API Transforming the above list into key store management subprocedures leads to the following list of key management function. I’ve specified the Validation List API(s) that the subprocedure exploits in the rightmost column: AddDtkEnt() - Add data key entry - QsyAddValidationLstEntry ChgDtkEnt() - Change data key entry - QsyChangeValidationLstEntry RmvDtkEnt() - Remove data key entry - QsyRemoveValidationLstEntry VfyDtkEnt() - Verify data key entry - QsyFindValidationLstEntry GetDtkAtr() - Get data key attribute - QsyFindValidationLstEntry GetDtkRcd() - Get data key record - QsyFindValidationLstEntry FndTopDtkE() - Find top data key entry - QsyFindFirstValidationLstEntry FndNxtDtkE() - Find next data key entry - QsyFindNextValidationLstEntry
  • 30. Code and development: Validation list APIs All key management subprocedures employs the function usage APIs to ensure that only explicitly function usage authorized user profiles are allowed to perform the subprocedure key management function. All the subprocedures on the previous slide can be found in the APIs by Example articles covering the Cryptographic Services APIs that have been published in the System iNetwork Programming Tips Newsletter. Again, links to these articles are provided at the end of this presentation.
  • 31. Code and development: Key management APIs I’ve written a number of articles, code examples as well as CL commands demonstrating the use and taking advantage of the V5R4 key management APIs and key stores. The Cryptographic Services Key Management APIs at V5R4 covered so far in the APIs by Example second cryptographic article series: Load master key part (Qc3LoadMasterKeyPart) API Set master key (Qc3SetMasterKey) API Test master key (Qc3TestMasterKey) API Clear master key (Qc3ClearMasterKey) API Create key store (Qc3CreateKeyStore) API Translate key store (Qc3TranslateKeyStore) API Generate key record (Qc3GenKeyRecord) API Delete key record (Qc3DeleteKeyRecord) API Retrieve key record attributes (Qc3RetrieveKeyRecordAtr) API V5R4 Cryptographic Services Key Management APIs not covered yet: The Export Key (Qc3ExportKey) API The Extract Public Key (Qc3ExtractPublicKey) API The Import Key (Qc3ImportKey) API The Write Key Record (Qc3WriteKeyRecord) API V6R1 Cryptographic Service Key Management APIs not covered yet: The Retrieve Key Store File Attributes (Qc3RetrieveKeyStoreFileAtr) API The Retrieve Key Store Records (Qc3RetrieveKeyStoreRecords) API The Translate Key (Qc3TranslateKey) API
  • 32. Code and development: Key management CL commands APIs by Example Key Management CL commands at V5R4: Load Master Key Part (LODMSTKP) Set Master Key (SETMSTK) Test Master Key (TSTMSTK) Clear Master Key (CLRMSTK) Create Key Store (CRTKS) Translate Key Store (TRNKS) Generate Key Record (GENKR) Display Key Record Attributes (DSPKRA) Delete Key Record (DLTKR) Cryptographic Services Key Management CL commands at V6R1: Add Master Key Part (ADDMSTPART) Set Master Key (SETMSTKEY) Check Master KVV (CHKMSTKVV) Clear Master Key (CLRMSTKEY) Add Keystore File Entry (ADDCKMKSFE) Create Keystore File (CRTCKMKSF) Display Keystore File Entry (DSPCKMKSFE) Generate Keystore File Entry (GENCKMKSFE) Remove Keystore File Entry (RMVCKMKSFE) Translate Keystore File (TRNCKMKSF)
  • 33. More Information on the Web Cryptography documentation : Carol Woodbury: The Essential Guide to Encryption, April 2006 http://systeminetwork.com/node/60013 Beth Hagemeister: Cryptographic Services APIs: Key Management: http://systeminetwork.com/article/cryptographic-services-apis-key-management Bruce Schneier: Computer Security Articles http://www.schneier.com/essays-comp.html AES Algorithm: http://en.wikipedia.org/wiki/AES The Rijndael page: http://www.iaik.tugraz.at/Research/krypto/AES/old/~rijmen/rijndael/ Encrypting Credit Card Numbers in a Database: http://www.di-mgt.com.au/cryptoCreditcard.html An Introduction to Using Keys in Encryption: http://www.di-mgt.com.au/cryptokeys.html Encryption with International Character Sets: http://www.di-mgt.com.au/cryptoInternational.html Using Padding in Encryption: http://www.di-mgt.com.au/cryptopad.html
  • 34. More Information on IBM Websites IBM documentation: Educational White Paper: Protecting i5/OS Data with Encryption: http://www-03.ibm.com/servers/enable/site/education/abstracts/efbe_abs.html IBM System i Security: Protecting i5/OS Data with Encryption: http://www.redbooks.ibm.com/Redbooks.nsf/RedpieceAbstracts/sg247399.html?Open Cryptographic Services APIs V5R4: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/topic/apis/catcrypt.htm i5/OS: Cryptography concepts V5R4: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/topic/rzajc/rzajcconcepts.htm Scenario: Key Management and File Encryption Using the Cryptographic Services APIs V5R4: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/topic/apis/qc3Scenario.htm Cryptographic Services APIs 6.1: http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/apis/catcrypt.htm i5/OS: Cryptography concepts 6.1: http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/rzajc/rzajcconcepts.htm Cryptographic Services Key Management 6.1: http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/rzajc/rzajckeymgmt.htm Disk Encryption 6.1: http:// publib.boulder.ibm.com /infocenter/systems/ scope /i5os/ topic / rzaly / rzalyencrypt.htm Backing Up Encrypted Auxiliary Storage Pools 6.1: http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/rzaiu/rzaiuencryptasp.htm Saving and Restoring Master Keys 6.1: http://publib.boulder.ibm.com/infocenter/systems/scope/i5os/topic/rzajc/rzajcsavemasterkey.htm
  • 35. More Information on System iNetwork Previously published articles: Compliance Encryption: A System i Signature http://systeminetwork.com/article/compliance-encryption-system-i-signature If You're Using Random Numbers, You Really Need This New Command http://systeminetwork.com/article/if-youre-using-random-numbers-you-really-need-new-command APIs by Example: Cryptographic Services APIs, Part 1 : http://systeminetwork.com/article/apis-example-cryptographic-services-apis APIs by Example: Cryptographic Services APIs, Part 2 : http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-2 APIs by Example: Cryptographic Services APIs, Part 3 : http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-3 APIs by Example: Cryptographic Services APIs, Part 4 : http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-4 APIs by Example: Cryptographic Services APIs, Part 5 : http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-5 APIs by Example: Cryptographic Services APIs, Part 6 : http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-6 APIs by Example: Cryptographic Services APIs, Part 7 : http://systeminetwork.com/article/apis-example-cryptographic-services-apis-part-7
  • 36. More Information on System iNetwork Previously published articles - continued: APIs by Example: Crypto Key Management - Loading and Setting Master Keys: http://systeminetwork.com/article/apis-example-cryptographic-key-management-loading-and-setting-master-keys APIs by Example: Crypto Key Management - Testing and Clearing Master Keys: http://systeminetwork.com/article/apis-example-cryptographic-key-management-testing-and-clearing-master-keys APIs by Example: Crypto Key Management – Creating and Translating Key Stores: http://systeminetwork.com/article/apis-example-cryptographic-key-management-creating-and-translating-key-stores APIs by Example: Crypto Key Management – Creating, Displaying, and Deleting Key Records: http://systeminetwork.com/article/apis-example-cryptographic-key-management-%E2%80%93-creating-displaying-and-deleting-key-records APIs by Example: Crypto Key Management - Creating Data Key Stores and More: http://systeminetwork.com/article/apis-example-crypto-key-management-creating-data-key-stores-and-more APIs by Example: Crypto Key Management - Encrypt/Decrypt with Key Hierarchy: http://systeminetwork.com/article/apis-example-crypto-key-mgmt-encryptdecrypt-key-hierarchy APIs by Example: AES Encryption to Actual Field Length: http://systeminetwork.com/article/apis-example-aes-encryption-actual-field-length
  • 37. RPG & Beyond 2008 : Writing RPG Applications using the Cryptographic Services APIs – The End Presentation completed! Questions concerning presentation, encryption topics or code snippets can be directed to me at: [email_address] Thank you!