我有一个.NET应用程序.我需要将加密的文本值存储在文件中,然后在代码中的其他位置检索加密值并对其进行解密.
我不需要地球上最强大或最安全的加密方法,只需要说一些东西 - 我有加密的值,并且能够解密它.
我在网上搜索了很多以尝试使用密码术,但我发现的大多数例子都没有明确定义概念,最糟糕的是它们似乎是机器特定的.
从本质上讲,有人可以发送链接到易于使用的加密方法,该方法可以将字符串值加密到文件,然后检索这些值.
StackOverflow 的扩展库有两个不错的小扩展,可以使用 RSA 加密和解密字符串。我自己在这里使用过几次这个主题,但还没有真正测试过它,但它是一个 StackOverflow 扩展库,所以我认为它已经过测试并且稳定。
加密:
public static string Encrypt(this string stringToEncrypt, string key)
{
if (string.IsNullOrEmpty(stringToEncrypt))
{
throw new ArgumentException("An empty string value cannot be encrypted.");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");
}
System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters();
cspp.KeyContainerName = key;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true);
return BitConverter.ToString(bytes);
}
Run Code Online (Sandbox Code Playgroud)
解密:
public static string Decrypt(this string stringToDecrypt, string key)
{
string result = null;
if (string.IsNullOrEmpty(stringToDecrypt))
{
throw new ArgumentException("An empty string value cannot be encrypted.");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
}
try
{
System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters();
cspp.KeyContainerName = key;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
string[] decryptArray = stringToDecrypt.Split(new string[] { "-" }, StringSplitOptions.None);
byte[] decryptByteArray = Array.ConvertAll<string, byte>(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));
byte[] bytes = rsa.Decrypt(decryptByteArray, true);
result = System.Text.UTF8Encoding.UTF8.GetString(bytes);
}
finally
{
// no need for further processing
}
return result;
}
Run Code Online (Sandbox Code Playgroud)