How to write an extension method in C# with multiple parameters?

Viewed 8688

I write this extension method but I get only one param.

My C# code:

public static string ToEncrypt(this string key, string passWord)
{
    // Salt and IV is randomly generated each time, but is prepended to encrypted cipher text
    // so that the same Salt and IV values can be used when decrypting.  
    var saltStringBytes = Generate256BitsOfRandomEntropy();
    var ivStringBytes = Generate256BitsOfRandomEntropy();
    var plainTextBytes = Encoding.UTF8.GetBytes(key);

    using (var password = new Rfc2898DeriveBytes(passWord, saltStringBytes, DerivationIterations))
    {
        var keyBytes = password.GetBytes(Keysize / 8);

        using (var symmetricKey = new RijndaelManaged())
        {
            symmetricKey.BlockSize = 256;
            symmetricKey.Mode = CipherMode.CBC;
            symmetricKey.Padding = PaddingMode.PKCS7;

            using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
            {
                using (var memoryStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                        var cipherTextBytes = saltStringBytes;
                        cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                        cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                        memoryStream.Close();
                        cryptoStream.Close();

                        return Convert.ToBase64String(cipherTextBytes);
                    }
                }
            }
        }
    }
}

And I try to use this extension method:

CallBack Miss Parameter

enter image description here

I've searched in google but could not find a solution to my problem.

Thanks you all! Sorry for my bad English

2 Answers

I think you are trying to write a extension method to encrypt the password with a key. So you function header should be:

public static string ToEncrypt(this string passWord, string key)

Later you can use this extension like below:

string encrpted = password.ToEncrypt("your key here");

Your problem is your extension method is written for the string it’s acting upon to be the “key” and not the “password”

So your code, as it’s written, should be

var key = “some key”;
var encryptedpass = key.ToEncrypt(password);

Your code doesn’t even reference key but your extension method does.

Related