PHP Encryption & VB.net Decryption

后端 未结 4 598
有刺的猬
有刺的猬 2021-02-06 13:52

I\'m trying to do a simple task. Encypt a value in PHP and Decrypt it in my VB.net app. I figure I\'d use tripleDES or Rijdael 128 or 256

I though this should be simple

4条回答
  •  日久生厌
    2021-02-06 14:42

    We have some ciphers working between C# on .NET and PHP. I am not familiar with VB.net. I assume it uses the same crypto library System.Security.Cryptography.

    On PHP side, we switched from mcrypt to OpenSSL because some modes and paddings are not supported by mcrypt.

    As long as you use same algorithm (DES, AES etc), same mode (CBC, ECB etc), same padding (PKCS1, PKCS5), the cipher should work on both platforms.

    Example of encryption using AES-128 on PHP side using mcrypt,

        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128);
        $data = $this->paddingAlgorithm->padData($data, $blockSize);
        return $iv . mcrypt_encrypt($this->MCRYPT_DES, $keyBytes, $data, MCRYPT_MODE_CBC, $iv);
    

    Please note that we use PKCS7 padding but mcrypt doesn't support it so we have to write the padding algorithm. We also prepend the IV (Initial Vector) to the cipher text. You might store it somewhere else but you need that to decrypt.

    Here is the corresponding C# code to setup the cipher to decrypt,

        // create the underlying symmetric algorithm with the given name
        algorithm = (SymmetricAlgorithm)CryptoConfig.CreateFromName("RIJNDAEL");
        // set cipher mode
        algorithm.Mode = CipherMode.CBC;
        // set padding mode
        algorithm.Padding = PaddingMode.PKCS7;
    

提交回复
热议问题