I have to decrypt in PHP a string encoded with this C# class (it's here)
using System; using System.Security.Cryptography; using System.Text; public static class Encryption { public static string Encrypt(string input, string key) { byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input); TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider(); tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key); tripleDES.Mode = CipherMode.ECB; tripleDES.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tripleDES.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length); tripleDES.Clear(); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } public static string Decrypt(string input, string key) { byte[] inputArray = Convert.FromBase64String(input); TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider(); tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key); tripleDES.Mode = CipherMode.ECB; tripleDES.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tripleDES.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length); tripleDES.Clear(); return UTF8Encoding.UTF8.GetString(resultArray); } }
I've tried different examples found around on the web, but nothing seems to work. I think that the first problems comes with the $iv parameter in php mcrypt_generic_init and then another problem comes with padding that is missing in php functions. Can you please help me to convert the c# Decrypt function above in PHP? Thank you.
Even I tried today code for both PHP and C#
C#
Because the IV does not matter in ECB mode, we can ignore it. However, mcrypt isn't very lenient. We still need to provide an IV, even if it's fake.
Again, you'll only want to do this if you stick with ECB mode. ECB mode can be pretty awful. You might want to review the Wikipedia article on block cipher modes for more information.
The only thing not handled here is the padding. mcrypt doesn't let you pick the padding method, and does something different depending on the cipher. Generally, it does not add any padding at all.
If your padding method of choice uses NUL bytes, you'll need to pre-pad the data yourself to ensure interoperability. You can use
mcrypt_get_block_size
andstr_pad
with theSTR_PAD_RIGHT
option to do this.Likewise, you might need to trim NUL bytes off of the right after you decrypt. The second parameter to
trim
will help.