I have a PHP code sample showing how to decrypt a certain message. I'm trying to decrypt that message using C#, but no luck yet.
Here is what I'm trying:
public static string AesDecrypt(byte[] dataToDecrypt, byte[] key, byte[] iv)
{
using (var aes = new AesCryptoServiceProvider())
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.None;
//aes.KeySize = 256;
aes.Key = key;
aes.IV = iv;
using (var memoryStream = new MemoryStream(dataToDecrypt))
{
var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(key, iv), CryptoStreamMode.Read);
using (var reader = new StreamReader(cryptoStream))
{
return reader.ReadToEnd();
}
}
}
}
Here is how I'm calling the method:
var aesKey = GenerateSha256Hash(Encoding.ASCII.GetBytes("t-3zafRa"));
var aesIv = GenerateSha256Hash(Encoding.ASCII.GetBytes("St@cE4eZ"));
var ivString = ConvertByteArrayToSring(aesIv).Substring(0, 16);
// I'm getting a 24 byte array here, but message needs to be multiple of 16, isn't it?
var encryptedText = Convert.FromBase64String("RmVpUjU4VjJlcXp2dkN5UlhUODQzUT09");
var aesDecryptedBytes = AesDecrypt(encryptedText, aesKey, Encoding.ASCII.GetBytes(ivString));
Here are the User-defined methods from above:
public static byte[] GenerateSha256Hash(byte[] toBeHashed)
{
using (var sha256 = SHA256.Create())
{
return sha256.ComputeHash(toBeHashed);
}
}
public static string ConvertByteArrayToSring(byte[] bytes)
{
var builder = new StringBuilder();
foreach (var t in bytes)
{
builder.Append(t.ToString("x2"));
}
return builder.ToString();
}
The PHP code sample I have is bellow:
php > $secret_key = "t-3zafRa";
$secret_iv = "St@cE4eZ";
php > $encrypted_txt = "RmVpUjU4VjJlcXp2dkN5UlhUODQzUT09";
php > $encrypt_method = "AES-256-CBC";
php > $key = hash('sha256', $secret_key);
php > $iv = substr(hash('sha256', $secret_iv), 0, 16);
php > echo openssl_decrypt(base64_decode($encrypted_txt), $encrypt_method, $key, 0, $iv);
I'm getting correct value for Key, IV and even the message when I'm converting it from base64String but the final call to Openssl_Decrypt seems not working for me.
I'm getting an error which says "Input data is not a complete block", which is kind of expected, I tried to remove first and last 8 byte as IV from the message to make it a 16 byte, but I'm still getting jibberish.
What I'm missing here? Thanks.