1

This block of code used to have both the key and the iv set, taken from C# Encryption to PHP Decryption

I've attempted to change it to use a generated iv that is prepended to the resulting output. The encrypt works fine (testing decrypt is done via php and works great) however I can't get the same results with the C# decrypt function using the C# encrypted text. Can anyone point out what I'm overlooking?

The error I'm seeing is Bad PKCS7 padding. Invalid Length x where x varies.

private static readonly byte[] Key = Convert.FromBase64String("REMOVED");
private const int IvBytes = 32;

public static string Encrypt(string prm_text_to_encrypt)
{
    var sToEncrypt = prm_text_to_encrypt;

    var rj = new RijndaelManaged()
    {
        Padding = PaddingMode.PKCS7,
        Mode = CipherMode.CBC,
        KeySize = 256,
        BlockSize = 256,
        Key = Key,
    };
    rj.GenerateIV ();

    var encryptor = rj.CreateEncryptor();

    var msEncrypt = new MemoryStream();
    var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

    var toEncrypt = Encoding.ASCII.GetBytes(sToEncrypt);

    csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
    csEncrypt.FlushFinalBlock();

    var encrypted = msEncrypt.ToArray();

    return (Convert.ToBase64String(rj.IV.Concat(encrypted).ToArray()));
}

public static string Decrypt(string prm_text_to_decrypt)
{

    var sEncryptedString = prm_text_to_decrypt;

    var rj = new RijndaelManaged()
    {
        Padding = PaddingMode.PKCS7,
        Mode = CipherMode.CBC,
        KeySize = 256,
        BlockSize = 256,
        Key = Key
    };

    var decryptor = rj.CreateDecryptor();

    var tmp = Convert.FromBase64String(sEncryptedString);

    var fromEncrypt = new byte[tmp.Length];

    byte[] IV = tmp.Take(IvBytes).ToArray();
    byte[] sEncrypted = tmp.Skip(IvBytes).ToArray();
    rj.IV = IV;

    var msDecrypt = new MemoryStream(sEncrypted);
    var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

    csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

    return (Encoding.ASCII.GetString(fromEncrypt));
}
Community
  • 1
  • 1
Sym
  • 187
  • 2
  • 9

0 Answers0