Search code examples
c#genericsencryptioncryptographyencryption-symmetric

How to use generic type methods in C# when the generic type is absract, TSymmetricAlgorithm


I am trying to call this method:

public string Decrypt5<TSymmetricAlgorithm>(string input) where TSymmetricAlgorithm : SymmetricAlgorithm, new()
    {
        var pwdBytes = Encoding.UTF8.GetBytes(_seed);
        using (TSymmetricAlgorithm sa = new TSymmetricAlgorithm())
        {
            ICryptoTransform saDec = sa.CreateDecryptor(pwdBytes, pwdBytes);

            var encBytes = Convert.FromBase64String(input);

            var resultBytes = saDec.TransformFinalBlock(encBytes, 0, encBytes.Length);
            Debug.WriteLine(Encoding.UTF8.GetString(resultBytes));
            return Encoding.UTF8.GetString(resultBytes);
        }
    }

By calling Decrypt5<TSymmetricAlgorithm>("myEncryptedStringBlahblahxyz"); But I keep getting an error that I must use a non-abstract type with a public parameter-less type instead of TSymmetricAlgorithm. Is there a default TSymmetricAlgorithm subclass that I can use. What am I doing wrong? Thank you.


Solution

  • Turns out using RijndaelManaged object type did the trick. I found this out through trial and error. If anyone knows a fast way to find out all the native classes in C# that subclass a certain parent abstract class (SymmetricAlgorithm in this case), please feel free to let me know in comments for future reference. I'm new to C# :-)