0

I am using entity framework(WebAPI/C#/VS2019) and using below code to save file and display file.

Save Code

 Document document = new Document();
 var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(attachment_data);  //attachment_data is string
                    document.document_content=plainTextBytes;//document_content is  byte[]

                    db.Documents.Add(document);
                    db.SaveChanges();

Below code is used to show saved file

 [Route("api/documents/download")]
    [HttpGet]
    public HttpResponseMessage Download(int documentid)
    {
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var document = db.Documents.Where(e => e.id.Equals(documentid)).FirstOrDefault();

        if (document != null)
        {
            var stream = new System.IO.MemoryStream(document.document_content);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType =
                new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = document.name

            };
        }
        return result;
    }

Both Save file and downloading file is working fine. The issue is how to encrypt the file content before Saving to Database?I saw few SO links but most of the methods are taking string as input and string as output.Not sure which one will fit in this scenario.

F11
  • 3,703
  • 12
  • 49
  • 83
  • The top answer you've linked to turns the string into bytes for processing: `var plainTextBytes = Encoding.UTF8.GetBytes(plainText);` So just use your document bytes as plainTextBytes instead. – Rup Mar 27 '20 at 09:43
  • 1
    `Convert.FromBase64String(System.Convert.ToBase64String` seems like a good way of burning up cycles for no particular benefit. Why not just `document.document_content = plainTextBytes`? – Damien_The_Unbeliever Mar 27 '20 at 09:49
  • Most of encryption method work with a byte array and not a string to encrypt/decrypt. As far as I could see, your document is a byte array. – H.G. Sandhagen Mar 27 '20 at 10:02
  • You can use AES encryption to encrypt the file before saving into the database, and use it to decrypt the file after retrieve from the database. – Imad Abu Hayyah Mar 28 '20 at 01:32

0 Answers0