加密解密字符串
/// <summary>
/// 基于 ProtectedData 实现的加密解密字符串,可以跨windows用户使用,但是不能跨计算机使用
/// </summary>
public static class EncryptHelper
{
public static string Encrypt(string stringToEncrypt)
{
byte[] toEncrypt = UnicodeEncoding.UTF8.GetBytes(stringToEncrypt);
MemoryStream stream = new MemoryStream();
int bytesWritten = EncryptDataToStream(toEncrypt, null, DataProtectionScope.LocalMachine, stream);
stream.Close();
return Convert.ToBase64String(stream.ToArray());
}
public static string Decrypt(string encryptedString)
{
byte[] encrypted = Convert.FromBase64String(encryptedString);
MemoryStream stream = new MemoryStream(encrypted);
byte[] decryptData = DecryptDataFromStream(null, DataProtectionScope.LocalMachine, stream, encrypted.Length);
stream.Close();
return UnicodeEncoding.UTF8.GetString(decryptData);
}
private static int EncryptDataToStream(byte[] buffer, byte[] entropy, DataProtectionScope scope, Stream stream)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (buffer.Length <= 0)
{
throw new ArgumentException("buffer");
}
if (stream == null)
{
throw new ArgumentNullException("stream");
}
int length = 0;
byte[] encrptedData = ProtectedData.Protect(buffer, entropy, scope);
if (stream.CanWrite && encrptedData != null)
{
stream.Write(encrptedData, 0, encrptedData.Length);
length = encrptedData.Length;
}
return length;
}
private static byte[] DecryptDataFromStream(byte[] entropy, DataProtectionScope scope, Stream stream, int length)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
if (length <= 0)
{
throw new ArgumentException("length");
}
byte[] inBuffer = new byte[length];
byte[] outBuffer;
if (stream.CanRead)
{
stream.Read(inBuffer, 0, length);
outBuffer = ProtectedData.Unprotect(inBuffer, entropy, scope);
}
else
{
throw new IOException("Could not read the stream.");
}
return outBuffer;
}
}
分类:
代码收藏
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决