Occasionally generating random keys using a cryptographically secure random number generator is not feasible, such as when a key is actually a passcode. Key derivation comes into play when a passcode needs to be turned into a proper key.
Acceptable keys can be generated from a user’s passcode by using the same algorithms used for storing passcodes.
The code used in previous lessons for keyed hashes will be refactored. Before, a new random key was created every time the generate button was selected. Now, a hardcoded passcode will be used, and key derivation will be implemented to generate a good key from it.
From the ‘Workspace Explorer’ panel on the right with ‘SecurityBasics.src’ set as the current project expand ‘Business Processes’ and select ‘GenerateFileHash.bp.’
A previous line of code is commented out and replaced.
The first thing to do to derive a key from a passcode, so a passcode is needed. A UChar array is made for the passcode – Uchar [] ucaPasscode.
Then the passcode is hardcoded – Move (StringToUCharArray(”password”)) to ucaPasscode. Key derivation is then used to create a proper key from that – Get DeriveKey of oMyKDF (&ucaPasscode) ucaSalt (MinimumKeyBytes(ghoSecurity, C_SEC_HASH_CNG_HMAC_SHA256)) to ucaKey.
The salt value is added – Uchar [] ucaSalt. For this demonstration, the salt value will be left empty to see what happens.
The key derivation object also needs to be added. ‘cSecurePasscodeStorageMethod’ is dragged and dropped from the ‘DataFlex Security’ section of the ‘Class Palette’ on the left.
It is edited and renamed to “oMyKDF.” PBKDF2 will be used in this demonstration.
Run the program, and from VIEW on the top menu select ‘Generate file hash.’
Then select a file, press the GENERATE button and two algorithms should be generated. The output will remain the same every time the button is pushed because the passcode is hardcoded in this example.
CHALLENGE – Refactor this example to allow a user to enter a passcode, and replace the hardcoded key with the key derived from this passcode.