如何在C#中编写具有多个参数的扩展方法?

5
我编写了这个扩展方法,但只获得一个参数。
我的C#代码:
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);
                    }
                }
            }
        }
    }
}

我尝试使用这个扩展方法:

回调函数缺少参数

enter image description here

我在谷歌上搜索了,但是找不到解决我的问题的方法。

谢谢大家!对不起我的英语不好。


4
我不明白问题是什么。扩展方法是一种独立接收至少一个参数的方法。第一个参数的类型是该方法所在类的类型。因此,由于您的方法有两个参数,在调用为扩展方法时,它将只有一个参数:passWord。那么你的问题是什么? - Andrew
2
是的,就像@Andrew所说的那样,将第一个参数视为调用扩展方法的对象。您可能希望在方法声明中交换密钥和密码的顺序。 - Ben
我同意@Ben的观点,我认为那可能是你的问题。顺便说一下,你的方法应该被称为Encrypt,或者可能是ToEncrypted。而且我强烈反对有两个变量名如此相似:passwordpassWord - Andrew
如果这是用于存储用户密码,你应该对它们进行哈希处理,而不是加密。你永远不应该能够将用户的密码反向解密为明文。你应该将用户输入的密码的哈希值与数据库中存储的哈希值进行比较。如果这是用于用户密码,请研究最佳的密码存储方法。 - ProgrammingLlama
2个回答

18

我认为你正在尝试编写一个扩展方法,使用密钥对密码进行加密。

因此,你的函数头应该是:

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

之后您可以像下面这样使用此扩展:

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

2

您的问题在于您的扩展方法是针对其作用的字符串作为“键”,而不是“密码”编写的。

因此,按照您编写的方式,您的代码应该是:

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

您的代码甚至没有引用key,但是您的扩展方法确实有引用它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接