gpt4 book ai didi

c# - 我将如何做一些简单的文件加密和解密?

转载 作者:太空狗 更新时间:2023-10-29 23:11:47 27 4
gpt4 key购买 nike

我有一个 .NET 应用程序。我需要在文件中存储一个加密的文本值,然后在代码中的其他地方检索加密值,并对其进行解密。

我不需要地球上最强大或最安全的加密方法,只需要一些足以说明的东西 - 我已经加密了值,并且能够解密它

我在网上搜索了很多尝试使用密码学,但我发现的大多数示例都没有明确定义概念,最糟糕的是它们似乎是特定于机器的。

基本上,有人可以发送一个指向易于使用的加密方法的链接,该方法可以将字符串值加密到文件中,然后检索这些值。

最佳答案

StackOverflow 的扩展库有两个不错的小扩展,可以使用 RSA 加密和解密字符串。我用过题目here我自己试过几次,但还没有真正测试过,但它一个 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);
}

解密:

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;
}

关于c# - 我将如何做一些简单的文件加密和解密?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1483348/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com