日期:2014-05-18 浏览次数:20776 次
/// <summary> /// 使用指定的加密算法、用随机密钥加密字符串 /// </summary> /// <param name="Source">要加密的字符串</param> /// <returns>加密结果</returns> public string Encrypting(string Source,string Key) { #region temp string strTemp = Key; if(strTemp.Length * 8 > objCryptoService.LegalKeySizes[0].MaxSize) { // 如果密钥长度太长得话,截 strTemp = strTemp.Substring(0,objCryptoService.LegalKeySizes[0].MaxSize / 8); } if(strTemp.Length * 8 < objCryptoService.LegalKeySizes[0].MinSize) { // 如果密钥长度太短得的话,在右边补空格 strTemp = strTemp.PadRight(objCryptoService.LegalKeySizes[0].MinSize / 8); } if(objCryptoService.LegalKeySizes[0].SkipSize != 0 && (strTemp.Length * 8) % objCryptoService.LegalKeySizes[0].SkipSize != 0) { // 如果密钥长度不是密钥长度间隔单位的倍数,则补空格。 strTemp = strTemp.PadRight(objCryptoService.LegalKeySizes[0].MaxSize / 8); } byte[] _Key = System.Text.Encoding.Default.GetBytes(strTemp); objCryptoService.Key = _Key; objCryptoService.IV = _Key; #endregion // 创建内存中的数据流 System.IO.MemoryStream objMemoryStream = new System.IO.MemoryStream(); // 创建加密器 ICryptoTransform objEncryptor = objCryptoService.CreateEncryptor(); // 创建加密转换文件流的加密流 CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objEncryptor, CryptoStreamMode.Write); StreamWriter writer = new StreamWriter(objCryptoStream); writer.Write(Source); writer.Flush(); objCryptoStream.FlushFinalBlock(); // 获取输出 byte[] bytOut = new byte[objMemoryStream.Length]; objMemoryStream.Position = 0; objMemoryStream.Read(bytOut,0,bytOut.Length); string strDest = System.Convert.ToBase64String(bytOut); objCryptoService.Clear(); objMemoryStream.Close(); writer.Close(); return strDest; }