I wrote (what I thought to be) identical encryption functions in PHP and C#. However, encrypting the same string is not producing identical results. I'm no expert in either C# nor PHP so I was hoping someone might be able to spot the difference that for some reason I am not catching here.
PHP function:
function encrypt($string, $key) {
$result = NULL;
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}
//return $result;
return $result;
}
C# function:
public static string encrypt_php_data(string stringToEncrypt, string key)
{
var result = string.Empty;
for (int i = 0; i < stringToEncrypt.Length; i++)
{
string keychar = phpSubStr_replacement(key, (i % key.Length) - 1);
result += (char)(Convert.ToChar(stringToEncrypt.Substring(i, 1)) + Convert.ToChar(keychar));
}
return result;
}
private static string phpSubStr_replacement(string stringToGrab, int startIndex)
{
if (startIndex < 0)
{
// Take from end of string
return stringToGrab.Substring(stringToGrab.Length + startIndex, 1);
}
else
{
// Take from beginning of string
return stringToGrab.Substring(startIndex, 1);
}
}
Here are the results of encrypting identical strings:
String encrypted: 09/16/2011 15:27:45
password used: somekey
C# Result: ©¬©¤ «ª©¡
PHP Result: ©¬žž›š—©¤ – Ÿ«ª©¡š
Note:
Not all outputs vary from each other. I cannot understand why some are different, while others produce the same outcome, makes no sense.
I look forward to your responses,
Evan