C # & # 8596; Dynamic AES Key Exchange

I want to create an encrypted communication system with dynamic key exchange between C # and PHP. At the moment I have a working PHP encryption / decryption ↔ PHP and C # ↔ C # but for whatever reason it doesn't work PHP ↔ C #. The problem is that the decrypted line of C # code generates a longer result than PHP expected, but when viewing the output as a simple string, the data is the same. For example, the string "daa" sent from C # to PHP, the decoded length is 28, which is not what it should be. The same happens with a string posted from PHP to C #, I am getting compiler error ArgumentException: length

C # code:

public static string EncryptTest(string input)
{
    string key = "256 bit key (32 char)";

    input = Md5Sum(input).Substring(0, 4) + input;

    var encoding = new UTF8Encoding();
    var Key = encoding.GetBytes(key);
    byte[] encrypted;
    byte[] result;

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

            using (ICryptoTransform encryptor = rj.CreateEncryptor())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter writer = new StreamWriter(cs))
                        {
                            writer.Write(input);
                        }
                    }

                    encrypted = ms.ToArray();
                    result = new byte[rj.BlockSize / 8 + encrypted.Length];

                    // Result is built as: IV (plain text) + Encrypted(data)
                    Array.Copy(rj.IV, result, rj.BlockSize / 8);
                    Array.Copy(encrypted, 0, result, rj.BlockSize / 8, encrypted.Length);
                }
            }
        }
        finally
        {
            rj.Clear();
        }
    }
    return Convert.ToBase64String(result);
}

public static string DecryptTest(string input)
{
    string key = "256 bit key (32 char)";

    byte[] data = Convert.FromBase64String(input);

    if (data.Length < 32)
        return null;

    var encoding = new UTF8Encoding();
    var Key = encoding.GetBytes(key);

    using (RijndaelManaged aes = new RijndaelManaged())
    {
        aes.Padding = PaddingMode.PKCS7;
        aes.Mode = CipherMode.CBC;
        aes.KeySize = 256;
        aes.BlockSize = 256;
        aes.Key = Key;

        // Extract the IV from the data first.
        byte[] iv = new byte[aes.BlockSize / 8];
        Array.Copy(data, iv, iv.Length);
        aes.IV = iv;

        // The remainder of the data is the encrypted data we care about.
        byte[] encryptedData = new byte[data.Length - iv.Length];
        Array.Copy(data, iv.Length, encryptedData, 0, encryptedData.Length);

        using (ICryptoTransform decryptor = aes.CreateDecryptor())
        {
            using (MemoryStream ms = new MemoryStream(encryptedData))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader reader = new StreamReader(cs))
                    {
                        string output = reader.ReadToEnd();

                        if (output.Length < 4)
                            return null;

                        string dataHash = output.Substring(0, 4);
                        string dataInput = output.Substring(4);
                        string dataInputHash = Md5Sum(dataInput).Substring(0, 4);

                        if (dataHash != dataInputHash)
                            return null;

                        return dataInput;
                    }
                }
            }
        }
    }
}

private static string Md5Sum(string strToEncrypt)
{
    UTF8Encoding ue = new UTF8Encoding();
    byte[] bytes = ue.GetBytes(strToEncrypt);

    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] hashBytes = md5.ComputeHash(bytes);

    string hashString = "";

    for (int i = 0; i < hashBytes.Length; i++)
    {
        hashString += Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
    }

    return hashString.PadLeft(32, '0');
}

      

PHP code:

$key = "256 bit key (32 char)";

function iv()
{
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
    return mcrypt_create_iv($iv_size, MCRYPT_RAND);
}
function encrypt($data, $key32)
{
    # Prepend 4-chars data hash to the data itself for validation after decryption
    $data = substr(md5($data), 0, 4).$data;
    # Prepend $iv to decrypted data
    $iv = iv();
    $enc = $iv.mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key32, $data, MCRYPT_MODE_CBC, $iv);
    return base64_encode($enc);
}
function decrypt($data, $key32)
{
    $data = base64_decode($data);
    if ($data === false || strlen($data) < 32)
        return null;
    $iv = substr($data, 0, 32);
    $encrypted = substr($data, 32);
    $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key32, $encrypted, MCRYPT_MODE_CBC, $iv), "\0");
    if ($decrypted === false || is_null($decrypted) || strlen($decrypted) < 4)
        return null;
    $dataHash = substr($decrypted, 0, 4);
    $data = substr($decrypted, 4);
    if (substr(md5($data), 0, 4) !== $dataHash)
        return null; // it breaks here, md5 sum is not correct because of the length
    return $data;
} 

      

+3


source to share


1 answer


PHP / mcrypt does not use PKCS # 7 padding, it uses zero padding 0..n bytes, where n is the block size.


In PKCS # 7-pad for plaintext before encryption use:

$pad = $blockSize - (strlen($data) % $blockSize);
$pdata = $data . str_repeat(chr($pad), $pad);

      



to unlock the plaintext after decryption, just do:

$pad = ord($pdata[strlen($pdata) - 1]);
$data = substr($pdata, 0, strlen($pdata) - $pad);

      


PKCS # 7 is now a custom padding standard. Zero padding is not deterministic; it can modify the plaintext if the plaintext is null-terminated.

+2


source







All Articles