简体   繁体   中英

Cross platform (php to C# .NET) encryption/decryption with Rijndael Part 2

< Original Code From Here>

I came across this thread while googling. However after trying it out and making adjustments, I've come across a hurdle, hopefully someone can help me out a bit.

  1. The code above is fine but since the algorithm isn't really useful without making the IV change everytime, I tried using following code to generate iv but it kept saying "Specified key is not a valid size for this algorithm." in my C# debugger.

  2. I also tried outputting IV from the C# code, after decoding base 64 string the string length varies from 30 31 2X ==> basically just fluctuates for some reason.

  3. I also would like to change the KEY as well but couldn't due to similar reasons as the IV issue, so hopefully someone can help me out with that?

(I've tried the following from http://php.net/manual/en/function.mcrypt-encrypt.php , couldn't get it to work in harmony with C#, maybe once I fix the IV issue I'll be able to fix this as well?

  $key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3"); )

PHP========================

<?php
  $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
  $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  //$iv = "45287112549354892144548565456541";
  $key = "anjueolkdiwpoida";

  $text = "This is my encrypted message";
  $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
  $crypttext = urlencode($crypttext);
  $crypttext64=base64_encode($crypttext);
  print($crypttext64) . "\n<br/>";
  print(base64encode($iv)) . "\n<br/>";
?>

C#========================

string iv = Encoding.UTF8.GetString(Convert.FromBase64String("SOME IV STRING I COPY FROM BROSWER WITH ABOVE PHP LOADED"));
string kyy = "anjueolkdiwpoida";
//ciphertext is also SOME TXT STRING I COPIED FROM BROWSER WITH ABOVE PHP LOADED
string plainText = ValidationControls.DecryptRJ256(cipherText, kyy, iv);



public byte[] Decode(string str)
    {
        var decbuff = Convert.FromBase64String(str);
        return decbuff;
    }

    static public String DecryptRJ256(byte[] cypher, string KeyString, string IVString)
    {
        var sRet = "";

        var encoding = new UTF8Encoding();
        var Key = encoding.GetBytes(KeyString);
        var IV = encoding.GetBytes(IVString);

        using (var rj = new RijndaelManaged())
        {
            try
            {
                rj.Padding = PaddingMode.PKCS7;
                rj.Mode = CipherMode.CBC;
                rj.KeySize = 256;
                rj.BlockSize = 256;
                rj.Key = Key;
                rj.IV = IV;
                var ms = new MemoryStream(cypher);

                using (var cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
                {
                    using (var sr = new StreamReader(cs))
                    {
                        sRet = sr.ReadLine();
                    }
                }
            }
            catch (Exception exc) { Console.WriteLine(exc.Message); App.Current.Shutdown(); }
            finally
            {
                rj.Clear();
            }
        }

        return sRet;
    }
  1. I realized that .NET decoding for Base 64 string is really weird. When I called DecryptRJ256() I was sending in the Key and IV that I received from the php code by a series of conversion base64_string -> byte -> utf8_string before sending both into the function. The solution to this is to just send in the byte array directly and let DecryptRJ256() deal with it directly.

  2. After doing the above, the problem with automated Key and IV generation becomes apparent and no longer is a problem.

Code Modified From Question:

PHP

$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
$text = "This is my encrypted message";

$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);

$crypttext = base64_encode($crypttext);
$key= base64_encode($key);
$iv = base64_encode($iv);

C#

string plainText = ValidationControls.DecryptRJ256(Convert.FromBase64String("/*$CRYPTTEXT STRING FROM PHP*/"), Convert.FromBase64String("/*$KEY STRING FROM PHP*/"), Convert.FromBase64String("/*$ STRING FROM PHP*/"));

static public String DecryptRJ256(byte[] cypher, byte[] KeyString, byte[] IVString)
    {
        ...
        var Key = KeyString;
        //var Key = encoding.GetBytes(KeyString);
        var IV = IVString;
        //var IV = encoding.GetBytes(IVString);
        ...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM