一個可逆的DES和TripleDES方式加密類(downmoon原創)

using System;

using System
Security;

using System
Security
Cryptography;

using System
IO;

using System
Text;

namespace EncryptDownmoon


{


/**//// <summary>

/// EncryptSqlConn 的摘要說明

/// </summary>

public class EncryptSqlConn

{

public EncryptSqlConn()

{

if(mCSP ==null)

{

mCSP = SetEnc();

}

}


/**//// <summary>

/// 設置加密方式
為DES
為TripleDES

/// </summary>

/// <returns></returns>

public EncryptSqlConn(int EnMethod)

{

if(EnMethod==
)

{

lngEnMethod=
;

}

else

{

lngEnMethod=
;

}

if(mCSP ==null)

{

mCSP = SetEnc();

}

}


方法#region 方法


private SymmetricAlgorithm mCSP;

private int m_lngEnMethod=
;


/**//// <summary>

/// 加密方式
為DES
為TripleDES

/// </summary>

public int lngEnMethod

{

get

{

return m_lngEnMethod;

}

set

{

m_lngEnMethod=value;

}

}

private SymmetricAlgorithm SetEnc()

{

if(lngEnMethod==
)

{

return new DESCryptoServiceProvider();

}

else

return new TripleDESCryptoServiceProvider();

}

//測試鍵值

private string genKeyValue

{

get

{

mCSP
GenerateKey();

return Convert
ToBase
String(mCSP
Key);

}

}

//測試IV值

private string genIVValue

{

get

{

mCSP
GenerateIV();

return Convert
ToBase
String(mCSP
IV);

}

}


/**//// <summary>

/// 加密字串

/// </summary>

/// <param name=
Value
></param>

/// <returns></returns>

public string EncryptString(string Value)

{

ICryptoTransform ct;

MemoryStream ms;

CryptoStream cs;

byte[] byt;

ct = mCSP
CreateEncryptor(mCSP
Key
mCSP
IV);

//ct = mCSP
CreateEncryptor(genKeyValue
genIVValue);

byt = Encoding
UTF
GetBytes(Value);

ms = new MemoryStream();

cs = new CryptoStream(ms
ct
CryptoStreamMode
Write);

cs
Write(byt
byt
Length);

cs
FlushFinalBlock();

cs
Close();

return Convert
ToBase
String(ms
ToArray());

}



/**//// <summary>

/// 解密字串

/// </summary>

/// <param name=
Value
></param>

/// <returns></returns>

public string DecryptString(string Value)

{

ICryptoTransform ct;

MemoryStream ms;

CryptoStream cs;

byte[] byt;

ct = mCSP
CreateDecryptor(mCSP
Key
mCSP
IV);

//ct = mCSP
CreateDecryptor(genKeyValue
genIVValue);

byt = Convert
FromBase
String(Value);

ms = new MemoryStream();

cs = new CryptoStream(ms
ct
CryptoStreamMode
Write);

cs
Write(byt
byt
Length);

cs
FlushFinalBlock();

cs
Close();

return Encoding
UTF
GetString(ms
ToArray());

}

#endregion

}

}
From:http://tw.wingwit.com/Article/program/net/201311/12830.html