文章内容
2017/4/21 10:46:37,作 者: 黄兵
C# DES加密
密码学中,三重数据加密算法(英语:Triple Data Encryption Algorithm,缩写为TDEA,Triple DEA),或称3DES(Triple DES),是一种对称密钥加密块密码,相当于是对每个数据块应用三次数据加密标准(DES)算法。由于计算机运算能力的增强,原版DES密码的密钥长度变得容易被暴力破解;3DES即是设计用来提供一种相对简单的方法,即通过增加DES的密钥长度来避免类似的攻击,而不是设计一种全新的块密码算法。
下面采用C#实现DES的一种加密算法,
详细代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | using System; using System.Text; using System.Security.Cryptography; using System.IO; namespace BlogAppCore { public class Encryption { /// <summary> /// 加密字符串 /// </summary> /// <param name="strText">明文</param> /// <param name="encryptKey">密钥</param> /// <returns></returns> static string DesEncrypt( string strText, string encryptKey) { string outString = "" ; byte [] byKey = null ; byte [] IV = Encoding.Default.GetBytes(encryptKey); try { byKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, encryptKey.Length)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Mode = CipherMode.ECB; byte [] inputByteArray = Encoding.UTF8.GetBytes(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); outString = Convert.ToBase64String(ms.ToArray()); } catch (Exception) { outString = "" ; } return outString; } } } |
另外一个代码片段如下:
private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV) { //Create the file streams to handle the input and output files. FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(0); //Create variables to help with read and write. byte[] bin = new byte[100]; //This is intermediate storage for the encryption. long rdlen = 0; //This is the total number of bytes written. long totlen = fin.Length; //This is the total length of the input file. int len; //This is the number of bytes to be written at a time. DES des = new DESCryptoServiceProvider(); CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write); Console.WriteLine("Encrypting..."); //Read from the input file, then encrypt and write to the output file. while(rdlen < totlen) { len = fin.Read(bin, 0, 100); encStream.Write(bin, 0, len); rdlen = rdlen + len; Console.WriteLine("{0} bytes processed", rdlen); } encStream.Close(); fout.Close(); fin.Close(); }
参考文章:
评论列表