///
/// 基于 ProtectedData 实现的加密解密字符串,可以跨windows用户使用,但是不能跨计算机使用
///
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 <&#61; 0)
{
throw new ArgumentException("buffer");
}
if (stream &#61;&#61; null)
{
throw new ArgumentNullException("stream");
}
int length &#61; 0;
byte[] encrptedData &#61; ProtectedData.Protect(buffer, entropy, scope);
if (stream.CanWrite && encrptedData !&#61; null)
{
stream.Write(encrptedData, 0, encrptedData.Length);
length &#61; encrptedData.Length;
}
return length;
}
private static byte[] DecryptDataFromStream(byte[] entropy, DataProtectionScope scope, Stream stream, int length)
{
if (stream &#61;&#61; null)
{
throw new ArgumentNullException("stream");
}
if (length <&#61; 0)
{
throw new ArgumentException("length");
}
byte[] inBuffer &#61; new byte[length];
byte[] outBuffer;
if (stream.CanRead)
{
stream.Read(inBuffer, 0, length);
outBuffer &#61; ProtectedData.Unprotect(inBuffer, entropy, scope);
}
else
{
throw new IOException("Could not read the stream.");
}
return outBuffer;
}
}