c# - 如何在 C# 中编写具有多个参数的扩展方法?
问题描述
我写了这个扩展方法,但我只得到一个参数。
我的 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);
}
}
}
}
}
}
我尝试使用这种扩展方法:
我在谷歌搜索但找不到解决我的问题的方法。
谢谢大家!对不起,我的英语不好
解决方案
我认为您正在尝试编写扩展方法来使用密钥加密密码。所以你的函数头应该是:
public static string ToEncrypt(this string passWord, string key)
稍后您可以使用此扩展程序,如下所示:
string encrpted = password.ToEncrypt("your key here");
推荐阅读
- html - 为什么下拉列表会从右侧的窗口中消失?
- javascript - 搜索引擎 AND OR NOT () 查询解析器
- nativescript - Nativescript Android 不断崩溃
- c++ - 在我的程序中加载纹理的 Opengl 3.3 问题
- php - 如何使用下拉列表从数据库中获取数据并显示到 php mysql 的输入字段中?
- java - 如何修复:错误:不是封闭类:上下文
- c# - 如何在 TransactionScope 中返回 SqlFileStream 并使用或需要替代解决方案,c#
- python - 为什么我在调用随机整数时会出现值错误?
- javascript - 我可以在不丢失 LI 内容的情况下刷新此页面吗?
- r - 我可以子集索引列表和索引周围的行吗?