C# 加密与解密,经典MD5加密

时间:2024-10-11 19:21:49

效果图:

C# 加密与解密,经典MD5加密

首先引入命名空间:using System.Security.Cryptography;

源码:

#region 加密

private void btnKey_Click(object sender, EventArgs e)

{

txtShow.Text = Encode(txtSetKey.Text, txtKey.Text, txtIV.Text);

}

//加密

public static string Encode(string data, string Key_64, string Iv_64)

{

string KEY_64 = Key_64;// "VavicApp";

string IV_64 = Iv_64;// "VavicApp";

try

{

byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);

byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

int i = cryptoProvider.KeySize;

MemoryStream ms = new MemoryStream();

CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

StreamWriter sw = new StreamWriter(cst);

sw.Write(data);

sw.Flush();

cst.FlushFinalBlock();

sw.Flush();

return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

}

catch (Exception x)

{

return x.Message;

}

}

#endregion

3.解密效果图

C# 加密与解密,经典MD5加密

源码:

#region 解密

private void btnStr_Click(object sender, EventArgs e)

{

txtShow.Text = Decode(txtRedKey.Text, txtKey.Text, txtIV.Text);

}

//解密

public static string Decode(string data, string Key_64, string Iv_64)

{

string KEY_64 = Key_64;// "VavicApp";密钥

string IV_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位无符号数组

DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

MemoryStream ms = new MemoryStream(byEnc);

CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);

StreamReader sr = new StreamReader(cst);

return sr.ReadToEnd();

}

catch (Exception x)

{

return x.Message;

}

}

#endregion

© 手抄报圈