使用C#和SymmetricAlgorithm实现简单的加密 [英] Really simple encryption with C# and SymmetricAlgorithm
问题描述
我正在寻找一个非常简单的crypt / decrypt方法。我将永远使用相同的静态键。我知道这种方法的风险。目前我正在使用以下代码,但是在隐藏并分解相同的字符串(在字符串中间有一些垃圾)之后,它不会产生相同的结果。
I'm looking for a very simple crypt / decrypt method. I will be using always the same static key. I'm aware of the risks of this approach. Currently I'm using the following code but it does not generate the same result after crypting and decripting the same string (there is some garbage in the middle of the string).
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;
}
我可以改变任何需要的,没有限制(但我只想拥有在方法crypt和另一个解密而不共享变量之间)。
I can change whatever is needed, no limits (but I want just to have on method to crypt and another one to decrypt without sharing variables between them).
谢谢。
推荐答案
如果您不想自己处理密钥,请让操作系统为您执行。例如。请使用 Windows数据保护(DPAPI)。
If you don't want to handle keys yourself then let the operating system do it for your. E.g. use Windows Data Protection (DPAPI).
您可以编写自己的字符串
,版本 System.Security.Cryptography.ProtectedData.Protect
和< a href =http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.unprotect.aspx =noreferrer> 取消保护
方法通过使用如下方式:
You can write your own, string
-based, version of System.Security.Cryptography.ProtectedData.Protect
and Unprotect
methods by using something like:
public static string Crypt (this string text)
{
return Convert.ToBase64String (
ProtectedData.Protect (
Encoding.Unicode.GetBytes (text) ) );
}
public static string Derypt (this string text)
{
return Encoding.Unicode.GetString (
ProtectedData.Unprotect (
Convert.FromBase64String (text) ) );
}
这篇关于使用C#和SymmetricAlgorithm实现简单的加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!