Generating Random Bytes

This example shows how the CRandom::GenerateRandomBytesL() method is used to populate a descriptor with a series of random bytes.

using namespace CryptoSpi;

//Create a pointer to store the factory-generated random implementation object
CRandom* randomImpl = NULL;

//Calling the CreateRandomL() method of the random factory class 
//creates a new CRandom object    
TRAPD(err, CRandomFactory::CreateRandomL(randomImpl, KRandomUid, NULL));

if(randomImpl && (err == KErrNone))
    {    
    //Create an 8 bit descriptor 50 bytes long with a max length of 50 bytes
    TBuf8<50> randomStr(50);
 
    //Passing the 8 bit descriptor to the CRandom::GenerateRandomBytesL() 
    //method fills it with random bytes. If there is no memory available 
    //or any problems occur, the method may leave.    
    randomImpl->GenerateRandomBytesL(randomStr); 
    }

//Destroy the random implementation object    
delete randomImpl;
randomImpl = NULL;