Q: How can I encrypt/decrypt data using AES CBC+CTS (ciphertext stealing) mode in PHP? I have to encrypt and decrypt data in AES CTS mode (ciphertext stealing, sometimes referred as AES-XTS) in PHP to interoperate with a remote system written in .NET platform. In .NET 4, this mode is supported natively.
For PHP, I cannot find a solution, based on the manual, mcrypt does not seem to have support for this mode.
Could anyone please explain the difference between plain CBC and CBC-CTS? Is it possible to make the latter work in PHP with using existing modules/libraries?

A: This is the steps from the wikipedia article interjected with my comments explaining the  


*

*LDn = Decrypt (K, Cn−1). Decrypt the second to last ciphertext block(the second to last 128bit/16 byte chunk chunk), using zeros as IV.
You can do this with the standard PHP mcrypt function, just pass 
$second_to_last_cipher=array_slice($your_cipher_text_byte_array,count($your_cipher_text_byte_array)-32,16)
to mcrypt_decrypt with a null Iv
$second_to_last_clear = mcrypt_decrypt"MCRYPT_RIJNDAEL_128",$key,$second_to_last_ciphe)

*Cn = Cn || Tail (Dn, B−M). Pad the ciphertext to the nearest multiple of the block size using the last B−M bits of block cipher decryption of the second-to-last ciphertext block.
Copy the last n bytes of the value you just decrypted into the last block of ciphertext.
$n = 16 - ($second_to_last_clear % 16) 
Then use array copy to copy the data 

*Swap the last two ciphertext blocks.
Simply switch the swap the contents of the last and second two last cells in your ciphertext array

*Decrypt the ciphertext using the standard CBC mode up to the last block.
make the standard decryption call.

*Exclusive-OR the last ciphertext (was already decrypted in step 1) with the second last ciphertext.  
Self explanatory. 

*Truncate the plaintext to the length of the original ciphertext.


A: I have found an implementation of AES algorithm in C, you can find it with source code here.
The author's older implementation was used in Android. So I think the implementation would be very promising.
Finally, after you have downloaded the source code, then check the file aesxam.c, there is a very good example of CTS with CBC for file encryption.
All credits go to Brian Gladman.

Brian Gladman now maintains his own github repo for AES.
