using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
using System.Security.Cryptography;
using System.IO;
namespace StringDecEncUtility.Tools
{
class DecEncWithBase64
{
//用Base64简单加密
public static string EncryptStringWithBase64(string InputString)
{
byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(InputString);
string str = Convert.ToBase64String(data);
return str;
}
//用Base64简单解密
public static string DecryptStringWithBase64(string InputString)
{
//string strconn = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
byte[] data = Convert.FromBase64String(InputString);
string str = System.Text.ASCIIEncoding.ASCII.GetString(data);
return str;
}
}
public class CryptionData
{
private byte[] SecureKey;
private byte[] EncryptionIV;
// The length of initialization vector should be 8 byte
//private static Byte[] EncryptionIV = Encoding.Default.GetBytes("abcdefgh");
/// <summary>
/// Constructor
/// </summary>
/// <param name="EncryptionString">SecureKey</param>
public CryptionData(string SecureKey, string EncryptionIV)
{
this.SecureKey = System.Text.Encoding.UTF8.GetBytes(SecureKey);
this.EncryptionIV = System.Text.Encoding.UTF8.GetBytes(EncryptionIV);
}
/// <summary>
/// 加密算法加Base64同时生成
/// </summary>
public string EncryptionByteData(string InputString)
{
byte[] SourceData = System.Text.Encoding.UTF8.GetBytes(InputString);
try
{
//生成 DESCryptoServiceProvider 对象
DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
//设置密钥和IV
desProvider.Key = SecureKey;
desProvider.IV = EncryptionIV;
//生成 MemoryStream 对象
MemoryStream ms = new MemoryStream();
//生成 Encryptor
ICryptoTransform encrypto = desProvider.CreateEncryptor();
//生成 CryptoStream 对象
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
//加密源数据
cs.Write(SourceData, 0, SourceData.Length);
cs.FlushFinalBlock();
//返回加密后结果
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception ex)
{
return ex.Message;
}
}
public string DecryptionByteData(string InputString)
{
byte[] SourceData = new byte[InputString.Length];
try
{
//生成 DESCryptoServiceProvider 对象
DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
//设置密钥和IV
desProvider.Key = SecureKey;
desProvider.IV = EncryptionIV;
SourceData = Convert.FromBase64String(InputString);
MemoryStream ms = new MemoryStream();
ICryptoTransform encrypto = desProvider.CreateDecryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
cs.Write(SourceData, 0, SourceData.Length);
cs.FlushFinalBlock();
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}