using System;
using System.IO;
using System.Text;
using System.Security.Permissions;
using System.Security.Cryptography;
public class Util
{
public Util()
{
}
// Encrypt a string
public static string EncryptAndBase64(string val, ICryptoTransform trans)
{
byte[] buf = UnicodeEncoding.Unicode.GetBytes(val);
MemoryStream memStream = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(memStream, trans, CryptoStreamMode.Write);
cryptStream.Write(buf, 0, buf.Length);
cryptStream.FlushFinalBlock();
cryptStream.Clear();
Array.Clear(buf, 0, buf.Length);
buf = memStream.GetBuffer();
val = Convert.ToBase64String(buf, 0, (int)memStream.Length);
Array.Clear(buf, 0, (int)memStream.Length);
return val;
}
// Decrypt an encrypted string
public static string DecryptFromBase64(string base64str, ICryptoTransform trans)
{
byte[] buf = Convert.FromBase64String(base64str);
MemoryStream memStream = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(memStream, trans, CryptoStreamMode.Write);
cryptStream.Write(buf, 0, buf.Length);
cryptStream.FlushFinalBlock();
cryptStream.Clear();
Array.Clear(buf, 0, buf.Length);
buf = memStream.GetBuffer();
string ret = UnicodeEncoding.Unicode.GetString(buf, 0, (int)memStream.Length);
Array.Clear(buf, 0, (int)memStream.Length);
memStream.Close();
return ret;
}
// Encrypt to File
public static void Encrypt2File(MemoryStream memStream, ICryptoTransform ict, string filePath)
{
FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Write, filePath);
perm.Demand();
Stream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
try
{
CryptoStream cryptStream = new CryptoStream(memStream, ict, CryptoStreamMode.Read);
int read = 0;
byte[] buf = new byte[4096];
while (true)
{
read = cryptStream.Read(buf, 0, buf.Length);
if (read == 0)
break;
fileStream.Write(buf, 0, read);
}
cryptStream.Clear();
}
finally
{
fileStream.Close();
}
}
}