|
||
This example demonstrates how to process a small data file (approximately
10k) and retrieve an MD5 hash representation of its contents.
#include <f32file.h>
#include <legacyselector.h>
#include <cryptohashapi.h>
//The CryptoSpi namespace is used to differentiate the CryptoSPI
//classes from the legacy APIs
using namespace CryptoSpi;
//Create and initialise a pointer for the hash implementation object
CHash* hashImpl = NULL;
//If successful, the CreateHashL() method creates a hash implementation object
//which is assigned to the hashImpl pointer
TRAPD(err, CHashFactory::CreateHashL(hashImpl,
KMd5Uid,
KHashModeUid,
NULL,
NULL));
//Having successfully instantiated the hash implementation, the next stage is
//to read the file from disk and compute the MD5 hash of the file
if (hashImpl && (err == KErrNone))
{
RFs fsSession;
//Create a connection to the file server
User::LeaveIfError(fsSession.Connect());
RFile sourceFile;
CleanupClosePushL(sourceFile);
//Open the source file passing in the file server session handle, source
//file path and file access mode (read-only)
User::LeaveIfError(sourceFile.Open(fsSession, _L("c:\\testdata\\smallHash.dat"), EFileRead));
//Retrieve the size of the data file using the Size()
//method of the RFile object
TInt sourceLength = 0;
User::LeaveIfError(sourceFile.Size(sourceLength));
//Create a heap based descriptor allocating enough memory to store the
//contents of the data file
HBufC8* sourceData = HBufC8::NewL(sourceLength);
CleanupStack::PushL(sourceData);
//Create a modifiable pointer descriptor and use the Des() method in
//order to read the contents of the data file into the heap based descriptor
TPtr8 sourcePtr = sourceData->Des();
sourceFile.Read(sourcePtr);
//Calling the implementation object's Hash() method, passing in the heap
//based descriptor, processes the data in the file and constructs the resulting
//hashed value which is returned within a TPtrC8.
TPtrC8 hashData(hashImpl->Hash(*sourceData));
CleanupStack::PopAndDestroy(sourceData);
//Cleanup the Source RFile
CleanupStack::PopAndDestroy();
//Close the file server session
fsSession.Close();
}
//Destroy the remaining Hash implementation object
delete hashImpl;
hashImpl = NULL;