效果图:
首先引入命名空间:usingSystem.Security.Cryptography;
源码:
#region加密
privatevoidbtnKey_Click(objectsender,EventArgse)
{
txtShow.Text=Encode(txtSetKey.Text,txtKey.Text,txtIV.Text);
}
//加密
publicstaticstringEncode(stringdata,stringKey_64,stringIv_64)
{
stringKEY_64=Key_64;//"VavicApp";
stringIV_64=Iv_64;//"VavicApp";
try
{
byte[]byKey=System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[]byIV=System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
DESCryptoServiceProvidercryptoProvider=newDESCryptoServiceProvider();
inti=cryptoProvider.KeySize;
MemoryStreamms=newMemoryStream();
CryptoStreamcst=newCryptoStream(ms,cryptoProvider.CreateEncryptor(byKey,byIV),CryptoStreamMode.Write);
StreamWritersw=newStreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
returnConvert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length);
}
catch(Exceptionx)
{
returnx.Message;
}
}
#endregion
3.解密效果图
源码:
#region解密
privatevoidbtnStr_Click(objectsender,EventArgse)
{
txtShow.Text=Decode(txtRedKey.Text,txtKey.Text,txtIV.Text);
}
//解密
publicstaticstringDecode(stringdata,stringKey_64,stringIv_64)
{
stringKEY_64=Key_64;//"VavicApp";密钥
stringIV_64=Iv_64;//"VavicApp";向量
try
{
byte[]byKey=System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[]byIV=System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
byte[]byEnc;
byEnc=Convert.FromBase64String(data);//把需要解密的字符串转为8位无符号数组
DESCryptoServiceProvidercryptoProvider=newDESCryptoServiceProvider();
MemoryStreamms=newMemoryStream(byEnc);
CryptoStreamcst=newCryptoStream(ms,cryptoProvider.CreateDecryptor(byKey,byIV),CryptoStreamMode.Read);
StreamReadersr=newStreamReader(cst);
returnsr.ReadToEnd();
}
catch(Exceptionx)
{
returnx.Message;
}
}
#endregion