ilipan的专栏

一、DES是一种数据加密标准,属于对称的加密算法体系。

下边是自己写的一个加密类:

using System;using System.IO;using System.Security.Cryptography;using System.Text;namespace ProtectFile{ public class Class1{public string Encrypt(string sourceString, string key, string iv){try{byte[] btKey = Encoding.UTF8.GetBytes(key);byte[] btIV = Encoding.UTF8.GetBytes(iv);DESCryptoServiceProvider des = new DESCryptoServiceProvider();using (MemoryStream ms = new MemoryStream()){byte[] inData = Encoding.UTF8.GetBytes(sourceString);try{using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))//加密器对象{cs.Write(inData, 0, inData.Length);cs.FlushFinalBlock();}return Convert.ToBase64String(ms.ToArray());}catch{return sourceString;}}}catch { }return "DES加密出错";}}}

解密类:

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Security.Cryptography;using System.Text;namespace ProtectFile{class Class2{public string Decrypt(string encryptedString, string key, string iv){byte[] btKey = Encoding.UTF8.GetBytes(key);byte[] btIV = Encoding.UTF8.GetBytes(iv);DESCryptoServiceProvider des = new DESCryptoServiceProvider();using (MemoryStream ms = new MemoryStream()){byte[] inData = Convert.FromBase64String(encryptedString);try{using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write)){//解密器对象cs.Write(inData, 0, inData.Length);cs.FlushFinalBlock();}return Encoding.UTF8.GetString(ms.ToArray());}catch{return encryptedString;}}}}}

解释:des.CreateDecryptor(btKey, btIV)中的两个参数为:(用于对称算法的密钥,用于对称算法的初始化向量);

因为是对称算法:所以加密和解密中两个参数必须相同。



,漫过心际的孤独,早已蔚然成冰,而你是这个季节里最美的音符。

ilipan的专栏

相关文章:

你感兴趣的文章:

标签云: