Importing Keys

This section describes how to import a key from a file using the keystore.

An externally generated key can be stored in the keystore using the import functionality. Use the CUnifiedKeyStore::ImportKey() function to import a key into the keystore.

The following steps explain the process of importing keys:


  1. Create a file system session using an RFs object.

  2. Create an object of type CUnifiedKeyStore using CUnifiedKeyStore::NewL() or CUnifiedKeyStore::NewLC() function.

  3. Initialize the member functions and keystore using the asynchronous function CUnifiedKeyStore::Initialize() .

  4. Open the file in read-only mode using the RFile object.

  5. Import the key using CUnifiedKeyStore::ImportKey() .

The required key is imported into the selected keystore.

Example

The following code snippet shows how to create a file system session object, initialize keystore and member functions, and import a key.

       
        
       
       //Create a file system session object
RFs iFs;
CleanupClosePushL(&iFs);



//Initialise the keystore and member functions
CUnifiedKeyStore* keyStore = CUnifiedKeyStore::NewL(iFs);
keyStore->Initialize(iStatus); //iStatus is a TRequestStatus object


...


HBufC8* keyData = NULL;
CleanupStack::PushL(keyData);



// Specify the path of the file containing the key details
TDriveUnit sysDrive (RFs::GetSystemDrive());
TFileName keyDataFile (sysDrive.Name());
keyDataFile.Append(_LIT("<path where key is located; relative to the system drive in this case.>"));


//Specify the filename
TFileName buf;
buf.FillZ();
buf.Copy(aDes); //Filename
keyDataFile.Append(buf); 


//Open the file in read-only mode
RFile file;
User::LeaveIfError(file.Open(iFs, keyDataFile, EFileRead));
CleanupClosePushL(file);

TInt fileSize = 0;
User::LeaveIfError(file.Size(fileSize));
HBufC8* iKeyData;

if (fileSize > 0)
    {
     iKeyData = HBufC8::NewMaxLC(fileSize);    
     TPtr8 data(iKeyData->Des());
     data.FillZ();
     User::LeaveIfError(file.Read(data, fileSize));
    }



//Import the key into the keystore
keyStore->ImportKey(0, iKeyData->Des(), usage, KLabel, accessType,
                TTime(0), keyInfo, iStatus);


//Clean up
CleanupStack::Pop(keyData);
CleanupStack::PopAndDestroy(); // file
CleanupStack::PopAndDestroy(); // iFs
      
Related concepts
Unified Keystore