We have the following simple encryption method in c#, we want write the same method in php7+
method in C#
using System.Security.Cryptography;
public string Encrypt(string strText, string encKey)
{
byte[] newEncKey = new byte[encKey.Length];
for (int i = 0; i < encKey.Length; i++)
newEncKey[i] = (byte)encKey[i];
try
{
TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();
byte[] bytes = Encoding.UTF8.GetBytes(strText);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(newEncKey, newEncKey), CryptoStreamMode.Write);
stream2.Write(bytes, 0, bytes.Length);
stream2.FlushFinalBlock();
return Convert.ToBase64String(stream.ToArray());
}
catch (Exception)
{
return string.Empty;
}
}
We want get the same encryption text with the same key in c# and php7+, We tried to use the following code in php
public function encryptData($key, $plainText)
{
$byte = mb_convert_encoding($key, 'ASCII');
$desKey = md5(utf8_encode($byte), true);
$desKey .= substr($desKey,0,8);
$data = mb_convert_encoding($plainText, 'ASCII');
// add PKCS#7 padding
$blocksize = mcrypt_get_block_size('tripledes', 'ecb');
$paddingSize = $blocksize - (strlen($data) % $blocksize);
$data .= str_repeat(chr($paddingSize), $paddingSize);
// encrypt password
$encData = mcrypt_encrypt('tripledes', $desKey, $data, 'ecb');
return base64_encode($encData);
}
, but encryption text using this method not match the encryption text in C# method.
Example :
C#:
String key = "234576385746hfgr";
String text = "hello";
Console.WriteLine(Encrypt(text, key));
// output: Hg1qjUsdwNM=
PHP:
$key = "234576385746hfgr";
$text = "hello";
echo encryptData($key, $text);
// output: SRdeQHyKJF8=
How to get the same encryption text in php7+, we want convert C# code to PHP!