using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace ConsoleApplication1
{
public class EncryptHelper
{
private SymmetricAlgorithm mCSP =
new TripleDESCryptoServiceProvider();
#region 加密解密函数
public string EncryptString(
string Value,
string sKey,
string sIV)
{
try
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
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(Value);
ms =
new MemoryStream();
cs =
new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt,
0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception ex)
{
return (
"Error in Encrypting " + ex.Message);
}
}
public string DecryptString(
string Value,
string sKey,
string sIV)
{
try
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
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(Value);
ms =
new MemoryStream();
cs =
new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt,
0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
catch (Exception ex)
{
return (
"Error in Decrypting " + ex.Message);
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(
string[] args)
{
EncryptHelper helper =
new EncryptHelper();
string oldValue =
"13800138000";
string sKey =
"qJzGEh6hESZDVJeCnFPGuxzaiB7NLQM5";
string sIV =
"andyliu1234=";
string newValue = helper.EncryptString(oldValue,sKey,sIV);
Console.WriteLine(
"加密后:"+ newValue);
string desValue = helper.DecryptString(newValue,sKey,sIV);
Console.WriteLine(
"解密后:"+ desValue);
Console.ReadLine();
}
}
}
更多资讯请关注我的公众号,定时分享各自技术: