diff -r 51a74ef9ed63 -r ae94777fff8f Symbian3/SDK/Source/GUID-598B6698-3518-50CA-98DE-D85CB255BA2D.dita --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Symbian3/SDK/Source/GUID-598B6698-3518-50CA-98DE-D85CB255BA2D.dita Fri Jun 11 12:39:03 2010 +0100 @@ -0,0 +1,74 @@ + + + + + +Secure stream encryption example code

This example covers:

Also, see:

Encrypting data with a password and writing it to a file
  • Supporting code for this example

+void CSecureStreamExample::WriteEncryptedDataL(const TDesC8& aInput, const TDesC& aFilename, const TDesC& aPassword) + { + // Open a stream to the output file + RFileWriteStream writeStream; + User::LeaveIfError(writeStream.Replace(iFs, aFilename, EFileShareExclusive | EFileWrite)); + CleanupClosePushL(writeStream); + + // Create a CPBEncryptElement object, passing details of the encryption we + // are using and the user's password + CPBEncryptElement* encryption = CPBEncryptElement::NewLC(aPassword, ECipherDES_CBC); + + // Store encryption data as the first thing in the stream + writeStream << encryption->EncryptionData(); + + // Create an REncryptStream - this wraps the write stream and encrypts + // everything written to it + REncryptStream encStream; + encStream.OpenL(writeStream, *encryption); + CleanupClosePushL(encStream); + + // Now we can simply write the plaintext to the encrypt stream - it gets + // encrypted automatically + encStream << aInput; + + // Commit the stream + encStream.CommitL(); + + // Free memory (writeStream, encryption, encStream) + CleanupStack::PopAndDestroy(3, &writeStream); + } +
Reading data from a file and decrypting it
  • Supporting code for this example

+HBufC8* CSecureStreamExample::ReadEncryptedDataLC(const TDesC& aFilename, const TDesC& aPassword) + { + // Open a stream to the input file + RFileReadStream readStream; + User::LeaveIfError(readStream.Open(iFs, aFilename, EFileRead)); + CleanupClosePushL(readStream); + + // Read the encryption data from the stream + CPBEncryptionData* encryptionData = CPBEncryptionData::NewLC(readStream); + + // Recreate the CPBEncryptElement object, using the encryption data from the + // file and the user's password + CPBEncryptElement* encryption = CPBEncryptElement::NewLC(*encryptionData, aPassword); + + // Create an RDecryptStream based on the read stream - this decrypts + // everything we read from it + RDecryptStream decStream; + decStream.OpenL(readStream, *encryption); + CleanupClosePushL(decStream); + + // Now we can read the plaintext straight from the stream + HBufC8* plaintext = HBufC8::NewL(decStream, KMaxTInt); + + // Free memory (readStream, encryptionData, encryption, decStream) + CleanupStack::PopAndDestroy(4, &readStream); + CleanupStack::PushL(plaintext); + + // Return plaintext to the caller + return plaintext; + } +
\ No newline at end of file