I have code that uploads
And downloads files
ToAnd 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
ToDoIn 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)
container.CreateIfNotExistsAsync()
Dim blobContPermission As New BlobContainerPermissions()
blobContPermission.PublicAccess = BlobContainerPublicAccessType.Container
container.SetPermissions(blobContPermission)
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
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"))
contain.CreateIfNotExists()
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,
Brando
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
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)"
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.
Member
51 Points
187 Posts
how to encrypt file And decrypt files uploaded and downloaded from azure storage
Feb 11, 2020 02:36 PM|E.RU|LINK
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:
Star
9831 Points
3120 Posts
Re: how to encrypt file And decrypt files uploaded and downloaded from azure storage
Feb 12, 2020 08:45 AM|Brando ZWZ|LINK
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:
Then you could add below setting with value into web.config:
Then you could refer to below aspx codes:
Best Regards,
Brando
Member
51 Points
187 Posts
Re: how to encrypt file And decrypt files uploaded and downloaded from azure storage
Feb 14, 2020 09:50 AM|E.RU|LINK
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
Erica
Member
51 Points
187 Posts
Re: how to encrypt file And decrypt files uploaded and downloaded from azure storage
Feb 14, 2020 10:23 AM|E.RU|LINK
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