Question

I've seen a few posts about this, but yet I can't seem to get this to work, any ideas?

RESULTS:

C# Encrypted string test = O6qzYiLPCpbXUf8PjMHpcg==
php Encrypted string test = SdS1dN1ugyAVYGFzHiTayg==

C# Code

public static string EncryptString(string message, string KeyString, string IVString)
{
    byte[] Key = ASCIIEncoding.UTF8.GetBytes(KeyString);
    byte[] IV = ASCIIEncoding.UTF8.GetBytes(IVString);

    string encrypted = null;
    RijndaelManaged rj = new RijndaelManaged();
    rj.Key = Key;
    rj.IV = IV;
    rj.Mode = CipherMode.CBC;

    try
    {
        MemoryStream ms = new MemoryStream();

        using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
        {
            using (StreamWriter sw = new StreamWriter(cs))
            {
                sw.Write(message);
                sw.Close();
            }
            cs.Close();
        }
        byte[] encoded = ms.ToArray();
        encrypted = Convert.ToBase64String(encoded);

        ms.Close();
    }
    catch (CryptographicException e)
    {
        Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
        return null;
    }
    catch (UnauthorizedAccessException e)
    {
        Console.WriteLine("A file error occurred: {0}", e.Message);
        return null;
    }
    catch (Exception e)
    {
        Console.WriteLine("An error occurred: {0}", e.Message);
    }
    finally
    {
        rj.Clear();
    }
    return encrypted;
}

string enctext = EncryptString("test", "qwertyuiopasdfghjklzxcvbnmqwerty", _"1234567890123456");

PHP

function aesenc($message, $keystring, $ivstring){
    $IV_UTF = mb_convert_encoding($ivstring, 'UTF-8');
    $KEY_UTF = mb_convert_encoding($keystring, 'UTF-8');

    return base64_encode( mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $KEY_UTF, $message, MCRYPT_MODE_CBC, $IV_UTF));
}

$enctext = aesenc("test", "qwertyuiopasdfghjklzxcvbnmqwerty", _"1234567890123456");
Was it helpful?

Solution

Found the answer, needed to add padding to the $message in php

function aesenc($message, $keystring, $ivstring){
    $IV_UTF = mb_convert_encoding($ivstring, 'UTF-8');
    $KEY_UTF = $keystring;

    return base64_encode( mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $KEY_UTF, addpadding($message), MCRYPT_MODE_CBC, $IV_UTF));
}
function addpadding($string, $blocksize = 16)
{
    $len = strlen($string);
    $pad = $blocksize - ($len % $blocksize);
    $string .= str_repeat(chr($pad), $pad);
    return $string;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top