Hi all,
I am really struggling with this and I have tried so many things I feel like I'm just chasing my tail.
Trying to have a matching encryption service in my .NET application and a PHP server, but no matter what I do, I can't seem to get these to agree, even when I use the same Key and IV. Any help would be greatly appreciated I you can see the inconsistency!
PHP
C#
And my test code:
Which returns basically the two encryptions (which I want to be the same):
I am really struggling with this and I have tried so many things I feel like I'm just chasing my tail.
Trying to have a matching encryption service in my .NET application and a PHP server, but no matter what I do, I can't seem to get these to agree, even when I use the same Key and IV. Any help would be greatly appreciated I you can see the inconsistency!
PHP
Code:
function pad($string, $blocksize = 32)
{
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
function encrypt($string)
{
$key = base64_decode("/RczyqV95+E4dC/owOzv1tncb5X2n+tzehoxdarJPmc=");
$iv = base64_decode("MFo4Fm64Y+58oZ2lOQ1bqT+P9WgdirhG9CkPAubwI1E=");
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $this->pad($string), MCRYPT_MODE_CBC, $iv));
}
Code:
private static SymmetricAlgorithm GetAlgorithm(SecureString password)
{
SymmetricAlgorithm algorithm = new RijndaelManaged();
algorithm.KeySize = 256;
algorithm.BlockSize = 256;
algorithm.Mode = CipherMode.CBC;
algorithm.Padding = PaddingMode.PKCS7;
algorithm.Key = Convert.FromBase64String("/RczyqV95+E4dC/owOzv1tncb5X2n+tzehoxdarJPmc=");
algorithm.IV = Convert.FromBase64String("MFo4Fm64Y+58oZ2lOQ1bqT+P9WgdirhG9CkPAubwI1E=");
}
public static string EncryptString(string clearText, string password)
{
SymmetricAlgorithm algorithm = GetAlgorithm(password);
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
Code:
var input = "test";
using (WebClient client = new WebClient())
{
byte[] response = client.UploadValues("[PHP script which takes $_POST val and returns encrypted byte array]", new NameValueCollection()
{
{ "test", input },
});
Console.WriteLine(Encoding.Default.GetString(response));
}
var encrypted = [Relavent Class].EncryptString(input);
Console.WriteLine(encrypted);
Code:
QrWFHlhzOsVRTD7wqEyGcnfb1PvMl6ZR8p9ES5SR0Tw= oGX2FLLQJuC0y8KvDKFWxiS3b6XLIU+60EYtNe0PExw=
Comment