Simple Crypt IO Device

From Qt Wiki
Revision as of 17:45, 14 January 2015 by Maintenance script (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Writing a Custom I/O Device with encryption via SimpleCrypt class

Creating a custom IO device was already described in Writing a Custom I/O Device. The encryption is used from Simple encryption with SimpleCrypt.

The example app can be found on gitorious: qtdevnet-wiki-mvc/qtdevnet-simplecryptiodevide [] .


The following code snippet shows how we would use the custom I/O device to encrypt data and store the result in a file:

The compressionMode and Integrity Protection can be changed if needed.

Also, if needed, a signal blockWritten can be connected.


The basic implementation is the same as in Custom I/O Device. The big difference is, that the data can’t be stored directly when the client writes it to the device, as the encryption/decryption is done block wise.

This means readData and writeData must be changed.

SimpleCryptIoDevice has a property blockSize. Data that is written is stored in an internal buffer of size blockSize. When the buffer size is reached, the data is encrypted and stored. This is needed, as SimpleCrypt (in it’s used version) does not allow to encrypt to a stream.


Note that because SimpleCrypt uses a header and both the compression and the data protection hash or checksum are calculated and stored at the the block level, using SimpleCryptDevice in this form results in a larger output stream than when using the SimpleCrypt class directly. Perhaps a future version of SimpleCrypt will support a streaming interface to increase efficiency in use cases such as these.


For reading, alway a complete block must be read from the device. Then the needed data is moved to the data buffer of the client. As there might be data left in the buffer, each read furst gets the data of the internal buffer. when it’s empty, new data is read from the underlying device.

The stored data always contains an int with the size of the encrypted buffer.


To write the data to the underlying device, first the current block needs to be filled. To achieve this, all data is attached to the buffer m_byteBuffer. unless the buffer is smaller than the block size, one block is removed of the buffer and stored in the underlying device.

writing one block is fairly easy. The block is encrypted by a call to SimpleCrypt::encryptToByteArray and the size of the encrypted data and the data itself is written to the underlying device.

To ensure no data is left when the device is closed, during close or destructor, the last buffer is flushed to the device.

That’s all.

Example application screenshot

Example App