How can I encrypt/decrypt data using AES CBC+CTS (ciphertext stealing) mode in PHP?

前端 未结 2 1430
感情败类
感情败类 2021-01-21 11:19

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

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 11:30

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

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

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

    3. Swap the last two ciphertext blocks.

      Simply switch the swap the contents of the last and second two last cells in your ciphertext array

    4. Decrypt the ciphertext using the standard CBC mode up to the last block.

      make the standard decryption call.

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

      Self explanatory.

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

提交回复
热议问题