how to encrypt file And decrypt files uploaded and downloaded from azure storage RRS feed

  • Question

  • User1717218719 posted

    I have code that uploads And downloads files To And from azure storage container. I am now looking For the files To be encrypded On upload And decrypted On download. also I would Like the file To be deleted from memory.

    I am struggling To find examples of code doing what im looking To Do In vb. any help With this would be great.

    Here is my code that uploads:

       Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim FileUpload1 As FileUpload = TryCast(FindControl("FileUpload1"), FileUpload)
            If FileUpload1.HasFile Then
                Dim fileID As Guid = Guid.NewGuid()
                Dim contentType As String = FileUpload1.PostedFile.ContentType
                Dim fileData As Byte() = New Byte(FileUpload1.PostedFile.InputStream.Length) {}
                FileUpload1.PostedFile.InputStream.Read(fileData, 0, fileData.Length)
                Dim originalName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
                Dim myFile As File = New File(contentType, originalName, fileData)
                originalName = FileUpload1.PostedFile.FileName
                FileUpload1.SaveAs(Server.MapPath("~/Uploads/" & fileID.ToString))     
                Dim storAcc As CloudStorageAccount = CloudStorageAccount.Parse(StorageConnStr)
                Dim blobClient As CloudBlobClient = storAcc.CreateCloudBlobClient()
                container = blobClient.GetContainerReference(containerName)
                Dim blobContPermission As New BlobContainerPermissions()
                blobContPermission.PublicAccess = BlobContainerPublicAccessType.Container
                Dim path2 = "myfile\folder\" & fileID.ToString
                Dim test = container.GetDirectoryReference("test")
                Dim blockBlob As CloudBlockBlob = container.GetBlockBlobReference(path2) 
                blockBlob.UploadFromFileAsync(Server.MapPath("~/Uploads/" & fileID.ToString))
        End Sub

    Tuesday, February 11, 2020 2:36 PM

All replies

  • User283571144 posted

    Hi E.RU,

    According to your description, I suggest you could use azure key valut to encrypt and decrypt your blob stroage files.

    More details about how to register the azure key valut and use it, you could refer to this article.

    You could firstly install below package:

    Install-Package Microsoft.Azure.ConfigurationManager
    Install-Package Microsoft.Azure.Storage.Common
    Install-Package Microsoft.Azure.Storage.Blob
    Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
    Install-Package Microsoft.Azure.KeyVault
    Install-Package Microsoft.Azure.KeyVault.Extensions

    Then you could add below setting with value into web.config:

        <add key="accountName" value="myaccount"/>
        <add key="accountKey" value="theaccountkey"/>
        <add key="clientId" value="theclientid"/>
        <add key="clientSecret" value="theclientsecret"/>
        <add key="container" value="stuff"/>

    Then you could refer to below aspx codes:

    Imports Microsoft.IdentityModel.Clients.ActiveDirectory
    Imports System.Configuration
    Imports Microsoft.Azure
    Imports Microsoft.Azure.Storage
    Imports Microsoft.Azure.Storage.Auth
    Imports Microsoft.Azure.Storage.Blob
    Imports Microsoft.Azure.KeyVault
    Imports System.Threading
    Imports System.IO
    Imports System.Threading.Tasks
    Public Class WebForm1
        Inherits System.Web.UI.Page
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Dim creds As StorageCredentials = New StorageCredentials(CloudConfigurationManager.GetSetting("accountName"), CloudConfigurationManager.GetSetting("accountKey"))
            Dim account As CloudStorageAccount = New CloudStorageAccount(creds, useHttps:=True)
            Dim client As CloudBlobClient = account.CreateCloudBlobClient()
            Dim contain As CloudBlobContainer = client.GetContainerReference(CloudConfigurationManager.GetSetting("container"))
            Dim cloudResolver As KeyVaultKeyResolver = New KeyVaultKeyResolver(AddressOf GetTokenAsync)
            'encrypt the blob stroage
            Dim rsa = cloudResolver.ResolveKeyAsync("https://contosokeyvault.vault.azure.net/keys/TestRSAKey1", CancellationToken.None).GetAwaiter().GetResult()
            Dim policy As BlobEncryptionPolicy = New BlobEncryptionPolicy(rsa, Nothing)
            Dim options As BlobRequestOptions = New BlobRequestOptions() With {
                .EncryptionPolicy = policy
            Dim blob As CloudBlockBlob = contain.GetBlockBlobReference("MyFile.txt")
            Using stream = System.IO.File.OpenRead("C:\Temp\MyFile.txt")
                blob.UploadFromStream(stream, stream.Length, Nothing, options, Nothing)
            End Using
            'decrypt the blob storage
            Dim policy2 As BlobEncryptionPolicy = New BlobEncryptionPolicy(Nothing, cloudResolver)
            Dim options2 As BlobRequestOptions = New BlobRequestOptions() With {
                .EncryptionPolicy = policy2
            Using np = File.Open("C:\data\MyFileDecrypted.txt", FileMode.Create)
                blob.DownloadToStream(np, Nothing, options2, Nothing)
            End Using
        End Sub
        Private Shared Async Function GetTokenAsync(ByVal authority As String, ByVal resource As String, ByVal scope As String) As Task(Of String)
            Dim authContext = New AuthenticationContext(authority)
            Dim clientCred As ClientCredential = New ClientCredential(CloudConfigurationManager.GetSetting("clientId"), CloudConfigurationManager.GetSetting("clientSecret"))
            Dim result As AuthenticationResult = Await authContext.AcquireTokenAsync(resource, clientCred)
            If result Is Nothing Then Throw New InvalidOperationException("Failed to obtain the JWT token")
            Return result.AccessToken
        End Function
    End Class

    Best Regards,


    Wednesday, February 12, 2020 8:45 AM
  • User1717218719 posted

    Hi Brando,

    Thank you for your reply. I have a question based on your repy. I have added your code to my application. with regards to the account name and account secret is it from the key vault I am getting these values? and the client id and secret from the azure active directory? I ask this as I used the Account name and account key that I had in my connection string (which has been working for my code) but is it correct to use storage account name and key?

    when I ran the code with this account name and account key I get the error: "Value cannot be null.
    Parameter name: AccountName"

    on the line "Dim account As CloudStorageAccount = New CloudStorageAccount(creds, useHttps:=True)"

    many thanks


    Friday, February 14, 2020 9:50 AM
  • User1717218719 posted

    I seemed To Get past that Error however now I have an Error "Response status code does not indicate success: 400 (BadRequest)"On line "Dim result As AuthenticationResult = Await authContext.AcquireTokenAsync(resource, clientCred)"I have tried To debug this And figure out the reson For this Error but With no luck.

    Do you have any idea the potential cause Of this Error Or any previous experience With this Error.

    Thanks For all your help

    Friday, February 14, 2020 10:23 AM