Secure stream encryption example code

This example covers:

Also, see:

Encrypting data with a password and writing it to a file


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


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;
         }