- int read_encrypted_file(fz_stream *stm, unsigned char *buf, int len){
- int n=0;
- rimage_aesd *aesd = (rimage_aesd *)stm->state;//get aesd from stm
- int64_t toPos;//position to read to from decryptedBuffer
- int64_t fromPos;//position to read from in decrypted buffer
- int whence = 0;
- int whence1 = 0;
- int lastSeekPos = stm->pos;
- int64_t blockStartPoint = 0;
- int64_t block_num = findBlocNum(stm->pos);//depending on the fileHandler position
- blockStartPoint = block_num*BLOCK_SIZE;
- aesd->blockNum = block_num;
- fromPos = stm->pos - blockStartPoint;
- toPos = fromPos + len;
- if(lastSeekPos > aesd->contentSize){
- //return -1;
- }
- whence = stm->pos - blockStartPoint;
- //lseek(aesd->filehandle, 1, -whence);//seek to block start to read data
- lseek(aesd->filehandle, 0, blockStartPoint);
- read(aesd->filehandle, aesd->encryptedBuffer, BLOCK_SIZE);
- rimage_decrypt_block(aesd);
- //to handle scenario where some data is in this block and remaining in next block
- if(toPos > BLOCK_SIZE){
- n += copy_decrypted_data(buf,aesd,fromPos,BLOCK_SIZE,n);
- aesd->blockNum++;
- read(aesd->filehandle, aesd->encryptedBuffer, BLOCK_SIZE);
- rimage_decrypt_block(aesd);
- toPos = len - n;
- fromPos = 0;
- if( (aesd->blockNum * BLOCK_SIZE) + toPos > aesd->contentSize){
- toPos = toPos - ((aesd->blockNum * BLOCK_SIZE) + toPos - aesd->contentSize);
- }
- }else{
- if(lastSeekPos+len > aesd->contentSize){
- toPos = toPos - (lastSeekPos+len - aesd->contentSize);
- }
- }
- n += copy_decrypted_data(buf,aesd,fromPos,toPos,n);
- whence = lastSeekPos + n;
- lseek(aesd->filehandle, 0, whence);//set file handle position correctly
- fz_assert_lock_held(stm->ctx, FZ_LOCK_FILE);
- if (n < 0)
- fz_throw(stm->ctx, "read error: %s", strerror(errno));
- return n;
- }