在c#中加密和解密文件 [英] encrypting and decrypting file in c#

查看:87
本文介绍了在c#中加密和解密文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它只适用于文本文件可以帮助我如何为所有类型的文件执行ex:pdf,word等

以下代码编码所有文件但在解密时's解码为一些char



plz帮我............



it''s work only for text file can any help me how to do it for all kind of files ex: pdf, word etc
the below code encoding all files but while in decrypting it''s decoded to some char

plz help me............

protected void FileUpload(int size,string CntType)
{ 
   conn.Open();
   SqlCommand cmd = new SqlCommand("insert into FileDetails values('" + File1.FileName + "','" + CntType + "','" + size + "','" + DateTime.Now + "')", conn);
   cmd.ExecuteNonQuery();
   cmd = new SqlCommand("select max(FileID) from FileDetails", conn);
   using (SqlDataReader dr = cmd.ExecuteReader())
   if (dr.Read())    
   {
      lstFile.Items.Clear();
      lstFile.Items.Add(" \t Keyword Encryption ---->  ");
      lstFile.Items.Add("----------------------------------------------------");
      string[] str=txtKeyword.Text.Split(',');
      foreach(string word in str)
      {
         string strEncrypt = Homomorphic.DesEncrypt(word.ToLower(), true);
         lstFile.Items.Add(" \t   " + strEncrypt);
         SqlCommand cmdindex = new SqlCommand("insert into Indexing values(" + dr.GetValue(0) + ",'"  + strEncrypt + "')", conn);
         cmdindex.ExecuteNonQuery();
      }
      dr.Close();
      lstFile.Items.Add("------------------------------------------------------------");
   }
}

protected void btnUpload_Click(object sender, System.EventArgs e)
{
   try
      {
	for(int i=0;i<request.files.count;i++)>
	{
	    if(Request.Files[i].FileName.Trim().Length >0) 
	    {
		HttpPostedFile file=Request.Files[i];
   	        if(file!=null && file.FileName.Length>0)
                {
                   string strmsg = string.Empty;
                   byte[] fileData = new byte[file.ContentLength];
                   file.InputStream.Read(fileData, 0, file.ContentLength);
                   strmsg = System.Text.Encoding.UTF8.GetString(fileData); 
                   string ps = Homomorphic.DesEncrypt(strmsg.ToLower(),true); 
                   using (StreamWriter writer = new StreamWriter(Path.Combine(GetCurDir(),                Path.GetFileName(file.FileName)), true))
                    {
                           writer.WriteLine(ps);
                           writer.Flush();
                    }
                    FileUpload(file.ContentLength,file.ContentType);
                    Response.Write("<script language='javascript'>alert('Encrypted & Uploaded !')</script>");
                    lstFile.Items.Add(" \t File Encryption  ----> ");
                    lstFile.Items.Add("------------------------------------------------------");
                    lstFile.Items.Add(" \t  " + ps);
                }
            }
         }
        BindData();
      }
      catch(Exception ex)
       {
            lblError.Text=ex.Message;
       }
}

推荐答案

你可以从word文件中读取所有文本然后加密/解密它。

你可以使用 Microsoft.Office.Interop.Word 来阅读表格 word

Excel Mircrosoft.office.Interop.Excel

我会发布代码来读取word文件。

you can read all text from word file and then encrypt/decrypt it.
You can use Microsoft.Office.Interop.Word to read form word
for Excel Mircrosoft.office.Interop.Excel
I will post code to read word file.
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
object miss = System.Reflection.Missing.Value;
object path = @"myDocument.docx";
object readOnly = true;
Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
string totaltext = "";
for (int i = 0; i < docs.Paragraphs.Count; i++)
{
totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
}
Console.WriteLine(totaltext);


using System;
using System.IO;
using System.Security.Cryptography;
public static byte[] Encypt(byte[] buffer, byte[] rgbSalt, string password, int iterations, PaddingMode paddingMode, CipherMode cipherMode)
        {
            using (Rijndael encryption = Rijndael.Create())
            {
                encryption.Padding = paddingMode;
                encryption.Mode = cipherMode;
                using (PasswordDeriveBytes passwordbuffer = new PasswordDeriveBytes(password, rgbSalt))
                {
                    encryption.Key = passwordbuffer.GetBytes(32);
                    encryption.IV = passwordbuffer.GetBytes(16);
                    passwordbuffer.IterationCount = iterations;
                    using (MemoryStream memory = new MemoryStream())
                    {
                        using (CryptoStream crypto = new CryptoStream(memory, encryption.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            crypto.Write(buffer, 0, buffer.Length);
                        }
                        return memory.ToArray();
                    }
                }
            }
        }


这篇关于在c#中加密和解密文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆