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
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.