日期:2014-05-17  浏览次数:20909 次

测试个加密文件!

namespace EncriptStringTest {
    class Program {
        static void Main (string[] args) {
            Console.WriteLine("Input The String to to Encrypt:");
            string strToEn = Console.ReadLine();    //待加密的字符串.
            string strEnResult = EncriptHelper.Encript(strToEn);    //调用方法,加密字符串.    
            Console.WriteLine("加密后的字符串为:\n" + strEnResult);
            Console.ReadKey();
        }
    }
    //加密类.
    class EncriptHelper {
        public static string enKey = "theKey";  //密匙.
        public static string Encript (string strToEn) {
            DESCryptoServiceProvider descrypt = new DESCryptoServiceProvider(); //加密字符串.
            byte[] keys = Encoding.Unicode.GetBytes(enKey);
            byte[] values = Encoding.Unicode.GetBytes(strToEn);
            MemoryStream mStream = new MemoryStream();  //内存流.
            //通过"内存流"创建贾米流对象.
            CryptoStream cStream = new CryptoStream(mStream, descrypt.CreateEncryptor(keys,values), CryptoStreamMode.Write);

            cStream.Write(values, 0, values.Length);    //写入内存.
            cStream.FlushFinalBlock();  //刷新写入的加密字符串.
            return Convert.ToBase64String(mStream.ToArray());
        }
    }
}
//我打"红字"部分报错了!
Specified key is not a valid size for this algorithm.

------解决方案--------------------
该加密算法,key值要8个字节长度。
------解决方案--------------------
byte[] values = Convert.FromBase64String(strToEn);