Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 3 从Windows Azure存储下载加密文件_Asp.net Mvc 3_Azure Storage_Azure Web Roles_Encryption Symmetric - Fatal编程技术网

Asp.net mvc 3 从Windows Azure存储下载加密文件

Asp.net mvc 3 从Windows Azure存储下载加密文件,asp.net-mvc-3,azure-storage,azure-web-roles,encryption-symmetric,Asp.net Mvc 3,Azure Storage,Azure Web Roles,Encryption Symmetric,我已经创建了一个MVC WebRole Window Azure应用程序,在该应用程序中,我使用对称算法(Rijndael)将加密文件上载到Azure blob存储,如下所示 控制器>动作是 [HttpPost] public ActionResult UploadImage_post(HttpPostedFileBase fileBase) { if (fileBase.ContentLength > 0) { // Retrieve a reference

我已经创建了一个MVC WebRole Window Azure应用程序,在该应用程序中,我使用对称算法(Rijndael)将加密文件上载到Azure blob存储,如下所示

控制器>动作是

[HttpPost]
public ActionResult UploadImage_post(HttpPostedFileBase fileBase)
{
    if (fileBase.ContentLength > 0)
    {
       // Retrieve a reference to a container 
       Microsoft.WindowsAzure.StorageClient.CloudBlobContainer blobContainer =
              _myBlobStorageService.GetCloudBlobContainer();

       Microsoft.WindowsAzure.StorageClient.CloudBlob blob =
                blobContainer.GetBlobReference(fileBase.FileName);
       using (BlobStream blobStream = blob.OpenWrite())
       {
             string encryptionKey = //somekey;
             byte[] file = new byte[fileBase.ContentLength];
             EncDecAlgo.EncryptBlobFile(file, blobStream, encryptionKey);
       }
    }
}

public void EncryptBlobFile(byte[] file, BlobStream bs, string key)
    {
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(key,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 
        0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
        Rijndael alg = Rijndael.Create();

        alg.Key = pdb.GetBytes(32);
        alg.IV = pdb.GetBytes(16);

        CryptoStream cs = new CryptoStream(bs,
           alg.CreateEncryptor(), CryptoStreamMode.Write);

        foreach (var data in file)
        {
            cs.WriteByte((byte)data);
        }

        cs.Close();
        bs.Close();
    }
上面的文件加密工作正常

下载的代码是

 public ActionResult DownloadFile(string filename)
    {
        // Retrieve reference to a previously created container.
        Microsoft.WindowsAzure.StorageClient.CloudBlobContainer blobContainer =
         _myBlobStorageService.GetCloudBlobContainer();

        Microsoft.WindowsAzure.StorageClient.CloudBlob blob =
            blobContainer.GetBlobReference(filename);
        blob.FetchAttributes();
        string encryptionKey = //same key used in encryption;
        using (BlobStream blobStream = blob.OpenRead())
        {
            EncDecAlgo.DecryptBlobFile(blobStream, encryptionKey, filename);
        }
    }

    public static void DecryptBlobFile(BlobStream bs, string key, string filePath)
    {
        try
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(key,
                new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 
        0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

        Rijndael alg = Rijndael.Create();

        alg.Key = pdb.GetBytes(32);
        alg.IV =  pdb.GetBytes(16);

        CryptoStream cs = new CryptoStream(bs,
            alg.CreateDecryptor(), CryptoStreamMode.Read);

        // Decrypt & Download Here
        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
        System.Web.HttpContext.Current.Response.ContentType = "application/" + Path.GetExtension(filePath).Replace(".", "");


        int data;
        while ((data = cs.ReadByte()) != -1)
        {
            if (data != 0)
            {
            }
            System.Web.HttpContext.Current.Response.OutputStream.WriteByte((byte)data);
            System.Web.HttpContext.Current.Response.Flush();

        }
        cs.Close();
        bs.Close();
        }
        catch
        {
        }
    }
下载时获取以下错误

Server cannot set content type after HTTP headers have been sent.

请提出一些解决方案。

这应该相当简单,希望这足以让您开始:

public class CloudFileResult : ActionResult
{
  private string m_FileName;
  private CloudBlobContainer m_Container;

  public CloudFileResult(string imageName, CloudBlobContainer container)
  {
    if (string.IsNullOrEmpty(imageName))
    {
      throw new ArgumentNullException("imageName");
    }
    if (container == null)
    {
      throw new ArgumentNullException("container");
    }

    m_FileName = imageName;
    m_Container = container;
  }

  public override void ExecuteResult(ControllerContext context)
  {
    context.HttpContext.Response.Clear();
    var blockBlob = m_Container.GetBlockBlobReference(m_FileName);
    blockBlob.FetchAttributes();
    context.HttpContext.Response.ContentType = blockBlob.Metadata["ContentType"];
    const string key = "my secret";
    using (var pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }))
    {
      using (var alg = RijndaelManaged.Create())
      {
        alg.Key = pdb.GetBytes(32);
        alg.IV = pdb.GetBytes(16);
        using (var stream = new CryptoStream(context.HttpContext.Response.OutputStream, alg.CreateDecryptor(), CryptoStreamMode.Write))
        {
          blockBlob.DownloadToStream(stream);
        }
      }
    }
  }
}

static void UploadFileToCloud(CloudBlobContainer container, HttpPostedFileBase file)
{
  const string key = "my secret";
  using (var pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }))
  {
    using (var alg = RijndaelManaged.Create())
    {
      alg.Key = pdb.GetBytes(32);
      alg.IV = pdb.GetBytes(16);

      var blockBlob = container.GetBlockBlobReference(file.FileName);
      using (var stream = new CryptoStream(file.InputStream, alg.CreateEncryptor(), CryptoStreamMode.Read))
      {
        blockBlob.UploadFromStream(stream);
      }
      blockBlob.Metadata.Add("ContentType", file.ContentType);
      blockBlob.SetMetadata();
    }
  }
}

static CloudBlobContainer GetContainer()
{
  string connection = "DefaultEndpointsProtocol=http;AccountName=AzureAccount;AccountKey=AzureAccountKey;";
  var account = CloudStorageAccount.Parse(connection);
  var client = account.CreateCloudBlobClient();
  var container = client.GetContainerReference("container");
  return container;
}
至于下载,您可以简单使用:

[HttpGet]
public ActionResult Index(string fileName)
{
  if (!string.IsNullOrEmpty(fileName))
  {
    return new CloudFileResult(fileName, GetContainer());
  }
  return View();
}
指针:

  • 我更喜欢使用托管加密算法
  • 我将原始文件的contenttype存储在blob元数据中(这样您就知道如何为其提供服务)
  • catch{}让我毛骨悚然,至少在某个地方记录了异常
  • 与其使用HttpContext.Response,不如创建自定义ActionResult
  • 总是处理可识别的东西

您可以尝试欺骗文件类型。如果文件为myReport.pdf,请重命名为myReportpdf.txt。我用一个应用程序拉一个crystal reports.rpt文件来做类似的事情。当我们将其发布到网站时,我们将其重命名为zip。@davek更改了文件扩展名,不会将其作为文本文件而不是pdf打开?而且它不工作..嘿@davek,实际上没有下载任何文件,我收到一个错误“服务器无法在发送HTTP头后设置内容类型”。我编辑了我的问题抱歉,我以为您最初可以下载txt文件类型。上传有效吗?是的,上传很有效。为了防止它对任何人都有帮助,我一直遇到一个可怕的错误:“.我在alg.Key行之前添加了以下行:alg.Padding=System.Security.Cryptography.PaddingMode.PKCS7;,并修复了它。大家好,在.Net core中有什么有用的链接可以这样做吗?