對稱EDS加解密方法

藍色水發表於2020-04-05
1.匯入兩個名稱空間:

using System.Security.Cryptography;

using System.Text.RegularExpressions;

 

2. 加密解密類:

private static readonly string sKey="qJzGEh6hESZDVJeCnFPGuxzaiB7NLQM3";//金鑰

private static readonly string sIV="qcDY6X+aPLw=";//向量,向量可以為空

private static SymmetricAlgorithm mCSP=new TripleDESCryptoServiceProvider();//構造一個對稱演算法

 

3.加密方法:

public static string EncryptDes(string source)

{

       ICryptoTransform ct;

       MemoryStream ms;

       CryptoStream cs;

       byte[] byt;

 

       string str=null;

      

       mCSP.Key=Convert.FromBase64String(sKey);

       mCSP.IV=Convert.FromBase64String(sIV);

       mCSP.Mode=System.Security.Cryptography.CipherMode.ECB;

       mCSP.Padding=System.Security.Cryptography.PaddingMode.PKCS7;

 

       ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);

 

       byt = Encoding.UTF8.GetBytes(source);

 

       ms = new MemoryStream();

       cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);

       cs.Write(byt, 0, byt.Length);

       cs.FlushFinalBlock();

 

       cs.Close();

 

       str=Convert.ToBase64String(ms.ToArray());

 

       return str;

}

 

4.機密方法:

public static string DecryptDes(string source)

{

       ICryptoTransform ct;

       MemoryStream ms;

       CryptoStream cs;

       byte[] byt;

 

       string str=null;

 

       mCSP.Key=Convert.FromBase64String(sKey);

       mCSP.IV=Convert.FromBase64String(sIV);

       mCSP.Mode=System.Security.Cryptography.CipherMode.ECB;

       mCSP.Padding=System.Security.Cryptography.PaddingMode.PKCS7;

 

       ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);

 

       byt = Convert.FromBase64String(source);

 

       ms = new MemoryStream();

       cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);

       cs.Write(byt, 0, byt.Length);

       cs.FlushFinalBlock();

 

       cs.Close();

 

       str= Encoding.UTF8.GetString(ms.ToArray());

 

       return str;

} 

相關文章