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