日期:2014-05-18 浏览次数:20874 次
/// <summary> /// 3DES加密方法 /// </summary> /// <param name="strPlain">明文</param> /// <param name="strDESKey">密钥</param> /// <param name="strDESIV">向量</param> /// <param name="ReturnBytes">标志位,如果返回数组则填写标志位</param> /// <returns>密文</returns> public static byte[] TripleDESEncrypt(string strPlain, string strDESKey, string strDESIV, bool ReturnBytes) { //把密钥转换成字节数组 byte[] bytesDESKey = ASCIIEncoding.ASCII.GetBytes(strDESKey); //把向量转换成字节数组 byte[] bytesDESIV = ASCIIEncoding.ASCII.GetBytes(strDESIV); //声明1个新的3DES对象 TripleDESCryptoServiceProvider tripledesEncrypt = new TripleDESCryptoServiceProvider(); //开辟一块内存流 MemoryStream msEncrypt = new MemoryStream(); //把内存流对象包装成加密流对象 CryptoStream csEncrypt = new CryptoStream(msEncrypt, tripledesEncrypt.CreateEncryptor(bytesDESKey, bytesDESIV), CryptoStreamMode.Write); //把加密流对象包装成写入流对象 StreamWriter swEncrypt = new StreamWriter(csEncrypt); //写入流对象写入明文 swEncrypt.WriteLine(strPlain); //写入流关闭 swEncrypt.Close(); //加密流关闭 csEncrypt.Close(); //把内存流转换成字节数组,内存流现在已经是密文了 byte[] bytesCipher = msEncrypt.ToArray(); //内存流关闭 msEncrypt.Close(); tripledesEncrypt.Clear(); return bytesCipher; } /// <summary> /// 3DES解密方法 /// </summary> /// <param name="bytes">包含密文的字节数组</param> /// <param name="lenght">字节数组中需要加密的字节长度</param> /// <param name="strDESKey">密钥</param> /// <param name="strDESIV">向量</param> /// <returns>明文</returns> public static string TripleDESDecrypt(byte[] bytes, int lenght, string strDESKey, string strDESIV) { //把密钥转换成字节数组 byte[] bytesDESKey = ASCIIEncoding.ASCII.GetBytes(strDESKey); //把向量转换成字节数组 byte[] bytesDESIV = ASCIIEncoding.ASCII.GetBytes(strDESIV); byte[] bytesCipher = new byte[lenght]; Array.Copy(bytes, bytesCipher, lenght); //声明1个新的3DES对象 TripleDESCryptoServiceProvider tripledesDecrypt = new TripleDESCryptoServiceProvider(); //开辟一块内存流,并存放密文字节数组 MemoryStream msDecrypt = new MemoryStream(bytesCipher); //把内存流对象包装成解密流对象 CryptoStream csDecrypt = new CryptoStream(msDecrypt, tripledesDecrypt.CreateDecryptor(bytesDESKey, bytesDESIV), CryptoStreamMode.Read); //把解密流对象包装成读出流对象 StreamReader srDecrypt = new StreamReader(csDecrypt); //明文=读出流的读出内容 string strPlainText = srDecrypt.ReadLine(); //读出流关闭 srDecrypt.Close(); //解密流关闭 csDecrypt.Close(); //内存流关闭 msDecrypt.Close(); //返回明文 tripledesDecrypt.Clear(); return strPlainText; } //然后用这两个方法对字符串加密: sMsg = "{\rtf1\ansi\ansicpg936\deff0\deflang1033\deflangfe2052{\fonttbl{\f0\fnil\fcharset134 \'cb\'ce\'cc\'e5;}} \viewkind4\uc1\pard\lang2052\f0\fs18 1 }"; byte[] ByteData = Security.TripleDESEncrypt(sMsg, strKey,strIV, true); //进行解密: string s = TripleDESDecrypt(ByteData, ByteData.Length,strKey,strIV); //解密后字符串为:{\rtf1\ansi\ansicpg936\deff0\deflang1033\deflangfe2052{\font