我正在寻找一种非常简单的加密/解密方法。我将始终使用相同的静态密钥。我知道这种方法的风险。目前我正在使用以下代码,但在加密和解密相同的字符串后它不会生成相同的结果(字符串中间有一些垃圾)。
public static string Crypt(this string text)
{
string result = null;
if (!String.IsNullOrEmpty(text))
{
byte[] plaintextBytes = Encoding.Unicode.GetBytes(text);
SymmetricAlgorithm symmetricAlgorithm = DES.Create();
symmetricAlgorithm.Key = new byte[8] {1, 2, 3, 4, 5, 6, 7, 8};
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(plaintextBytes, 0, plaintextBytes.Length);
}
result = Encoding.Unicode.GetString(memoryStream.ToArray());
}
}
return result;
}
public static string Decrypt(this string text)
{
string result = null;
if (!String.IsNullOrEmpty(text))
{
byte[] encryptedBytes = Encoding.Unicode.GetBytes(text);
SymmetricAlgorithm symmetricAlgorithm = DES.Create();
symmetricAlgorithm.Key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream memoryStream = new MemoryStream(encryptedBytes))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, symmetricAlgorithm.CreateDecryptor(), CryptoStreamMode.Read))
{
byte[] decryptedBytes = new byte[encryptedBytes.Length];
cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);
result = Encoding.Unicode.GetString(decryptedBytes);
}
}
}
return result;
}
我可以改变任何需要的东西,没有限制(但我只想有一个加密方法和另一个解密方法,而不在它们之间共享变量)。
谢谢。