加密解密字符串

复制代码
    /// <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;

}
}
复制代码
posted @   梦幻泡影  阅读(437)  评论(0编辑  收藏  举报
编辑推荐:
· 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语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示