Encrypting a file to me is akin to dealing with a very long string, feeding it into the hashing or encryption function to get another long encrypted string (or a hash in the case of hashing).

This process takes some good amount of time. I know that because I use HashTab to verify the integrity of the files I download off the Internet.  

How can ransomware like CTB-Locker or Crypt0l0cker encrypt their victims files instantly?

Recently a friend of mine was a victim of one of these ransomware and he could NOT open his files/photos from Ubuntu on his dual-OS machine even when the infection happened with MSWindows. This suggests the encryption does not happen on the fly when you open a file.  

I was at an OWASP talk where the speaker decompiled and analyzed a ransomware executable (for Windows) in front of us. There are many flavours of ransomware out there, so I can't speak to ransomware in general, but I can certainly talk about the one I saw. The general idea is that the ransomware executable contains the encryption public key needed to encrypt files using an asymmetric algorithm, for example RSA. The corresponding private / decryption key stays with the hackers so that no amount of reverse-engineering of the executable can give you the decryption key.

To actually encrypt a file, it does something similar to:


Skip the first 512 bytes of the file so that the file header stays intact.
Encrypt the next 1 MB using the embedded encryption key.
If the file is longer than this, leave the rest unencrypted.


The point is not to fully hide or protect the data, it's enough to make it un-parseable.

As for time, doing 1 MB of RSA is still slow and will still take several hours to crawl your HDD. 

I suspect that this specimen that I saw was just a lazy imitation of the full RSA-AES ransomware that Steffen Ullrich talked about in his answer - which is the one that you should really be worried about.
