|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace Mullivan.Cryptography
{
public static class Encryption
{
public static string Decrypt(string text, string INITVECT, string ENCKEY)
{
MemoryStream ms = null;
CryptoStream cs = null;
Byte[] result = null;
try
{
ENCKEY = CheckKey(ENCKEY);
INITVECT = CheckKey(INITVECT);
Byte[] buf = Convert.FromBase64String(text);
TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider();
ICryptoTransform cryptoTrans = tds.CreateDecryptor(ASCIIEncoding.ASCII.GetBytes(ENCKEY), ASCIIEncoding.ASCII.GetBytes(INITVECT));
ms = new MemoryStream();
cs = new CryptoStream(ms, cryptoTrans, CryptoStreamMode.Write);
cs.Write(buf, 0, buf.Length);
cs.FlushFinalBlock();
ms.Position = 0;
result = (Byte[])Array.CreateInstance(typeof(System.Byte), ms.Length);
ms.Read(result, 0, (int)ms.Length);
}
catch
{
return string.Empty;
}
finally
{
try
{
if (ms != null) ms.Close();
if (cs != null) cs.Close();
}
catch { }
}
return ASCIIEncoding.ASCII.GetString(result);
}
public static string Encrypt(string text, string INITVECT, string ENCKEY)
{
MemoryStream ms = null;
CryptoStream cs = null;
Byte[] result = null;
try
{
ENCKEY = CheckKey(ENCKEY);
INITVECT = CheckKey(INITVECT);
Byte[] inBytes = ASCIIEncoding.ASCII.GetBytes(text);
TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider();
ICryptoTransform cryptoTrans = tds.CreateEncryptor(ASCIIEncoding.ASCII.GetBytes(ENCKEY), ASCIIEncoding.ASCII.GetBytes(INITVECT));
ms = new MemoryStream();
cs = new CryptoStream(ms, cryptoTrans, CryptoStreamMode.Write);
cs.Write(inBytes, 0, inBytes.Length);
cs.FlushFinalBlock();
ms.Position = 0;
result = (Byte[])Array.CreateInstance(typeof(System.Byte), ms.Length);
ms.Read(result, 0, (int)ms.Length);
ms.Close();
cs.Close();
}
catch
{
return string.Empty;
}
finally
{
try
{
if (ms != null) ms.Close();
if (cs != null) cs.Close();
}
catch { }
}
return Convert.ToBase64String(result);
}
private static string CheckKey(string key)
{
if (key.Length >= 32)
return key;
while (key.Length < 32)
key += " ";
return key;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.